• Python

Command Palette

Search for a command to run...

Python Fundamentals
  • Python Variables
  • Python Operators
  • Python Input-Output
  • Python Type Conversion
Python Data Types
  • Python Strings
  • Python List
  • Python Tuple
  • Python Dictionnaries
  • Python Sets
Python Flow Control
  • Python Conditions
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
Python Functions
  • Python Functions
  • Python Arguments
  • Python Functions Scope
  • Python Recursion
Python Classes
  • Python Classes
  • Python Classes and Static Methods
  • Python Properties
  • Python Decorators
  • Python Error Handling

Create an Account

FREE

Join our community to access more courses.

Create Account

On this page

Building with Blueprints: Understanding Classes and ObjectsWhat are Classes and Objects?Defining a ClassCreating Objects (Instances)The Method (The Constructor)Object Attributes (Properties)Object Methods (Behaviors)Summary
      • Pricing
      • Blog

      Python Classes

      Building with Blueprints: Understanding Classes and Objects

      In Python, and many other programming languages, we often deal with data and the actions we perform on that data. Object-Oriented Programming (OOP) is a powerful way to think about and structure your code by bundling data and the functions that work on that data together.

      The fundamental concepts in OOP are classes and objects. Think of them as a way to model real-world things (like a dog, a car, or a user) or more abstract concepts (like a bank account or a geometric shape) within your program.

      This article will introduce you to these core building blocks of OOP in Python.

      What are Classes and Objects?

      Let's use an analogy to understand the difference between a class and an object:

      • A Class is like a blueprint for a house. It describes what the house will have (number of rooms, type of roof, color of walls) and potentially what it can do (open/close windows, turn on/off lights), but it's not a physical house you can live in.
      • An Object (also called an instance) is a specific house built from that blueprint. It has all the features defined in the blueprint (attributes like number_of_rooms, color) and can perform the actions (methods like open_window()), but it's a unique, physical entity with its own address and possibly its own specific color or variations not on the main blueprint.

      In programming terms:

      • A Class is a template that defines the structure (what data it holds) and the behavior (what actions it can perform) for a group of related objects.
      • An Object is a specific instance created from a class. Each object has its own set of data (attributes) but shares the behavior defined by the class (methods).

      Defining a Class

      You define a class using the class keyword, followed by the class name and a colon :. The body of the class is indented.

      By convention, class names in Python use CamelCase (each word starts with a capital letter, with no underscores).

      # Define a simple class
      class Dog:
          # The body of the class goes here
          pass # 'pass' is a placeholder, means 'do nothing'
      

      This defines a basic Dog class, but it doesn't do much yet. The class definition is like creating the blueprint; it doesn't create any actual dogs.

      Creating Objects (Instances)

      To create an object (an instance) from a class, you call the class name using parentheses, just like you call a function:

      # Define the Dog class (as above)
      class Dog:
          pass
      
      # Create two objects (instances) of the Dog class
      my_dog = Dog() # my_dog is an object of the Dog class
      your_dog = Dog() # your_dog is another object of the Dog class
      
      print(my_dog) # Output will show something like <__main__.Dog object at ...>
      print(your_dog) # Output will show a different object at a different memory address
      

      Each call to Dog() creates a new, distinct object in memory based on the Dog blueprint.

      The __init__ Method (The Constructor)

      When you create an object, you often want to give it some initial properties or set it up in a specific state. This is done using a special method called __init__ (pronounced "dunder init").

      The __init__ method is automatically called every time you create a new object from a class. It's often referred to as the constructor because it helps construct the object.

      The first parameter of any method in a class, including __init__, is always self. self is a reference to the instance of the object that is currently being created or used.

      class Dog:
          # The __init__ method takes self and other parameters
          def __init__(self, name, breed):
              # Use self to attach attributes to the object being created
              self.name = name    # Creates an attribute 'name' for the object
              self.breed = breed  # Creates an attribute 'breed' for the object
              print(f"A new dog named {self.name} has been created!")
      
      # Now, when creating a Dog object, we must provide name and breed arguments
      my_dog = Dog("Buddy", "Golden Retriever")
      your_dog = Dog("Lucy", "Poodle")
      

      Output:

      A new dog named Buddy has been created!
      A new dog named Lucy has been created!
      

      The arguments passed when calling Dog(...) are received by the parameters in __init__ (except for self, which Python handles automatically). Inside __init__, we use self.attribute_name = parameter_name to store these values as attributes of the specific object being created.

      Object Attributes (Properties)

      Attributes are variables that belong to an object. They represent the data or properties associated with that specific instance.

      You access an object's attributes using dot notation (object_name.attribute_name).

      class Dog:
          def __init__(self, name, breed):
              self.name = name
              self.breed = breed
      
      my_dog = Dog("Buddy", "Golden Retriever")
      your_dog = Dog("Lucy", "Poodle")
      
      # Accessing the attributes of my_dog
      print(f"My dog's name is {my_dog.name}")
      print(f"My dog's breed is {my_dog.breed}")
      
      # Accessing the attributes of your_dog
      print(f"Your dog's name is {your_dog.name}")
      print(f"Your dog's breed is {your_dog.breed}")
      

      Output:

      My dog's name is Buddy
      My dog's breed is Golden Retriever
      Your dog's name is Lucy
      Your dog's breed is Poodle
      

      Each object (my_dog, your_dog) has its own independent copies of the name and breed attributes.

      Object Methods (Behaviors)

      Methods are functions that are defined inside a class. They represent the behaviors or actions that objects created from the class can perform.

      Methods are defined just like regular functions using def, but they always have self as their first parameter, which refers to the object calling the method.

      class Dog:
          def __init__(self, name, breed):
              self.name = name
              self.breed = breed
      
          # Define a method called bark
          def bark(self):
              print(f"{self.name} says Woof! Woof!")
      
          # Define another method
          def describe(self):
              print(f"{self.name} is a {self.breed}.")
      

      You call an object's methods using dot notation (object_name.method_name()), just like accessing attributes, but with parentheses.

      my_dog = Dog("Buddy", "Golden Retriever")
      your_dog = Dog("Lucy", "Poodle")
      
      # Call the bark method on each object
      my_dog.bark()
      your_dog.bark()
      
      # Call the describe method
      my_dog.describe()
      

      Output:

      Buddy says Woof! Woof!
      Lucy says Woof! Woof!
      Buddy is a Golden Retriever.
      

      Inside the methods, you use self to access the object's own attributes (self.name, self.breed) or call other methods (self.another_method()).

      Summary

      • Object-Oriented Programming (OOP) uses classes and objects to structure code.
      • A Class is a blueprint or template defining attributes (data) and methods (behavior).
      • An Object is a specific instance created from a class.
      • Define a class using the class keyword.
      • Create an object by calling the class name (ClassName()).
      • The __init__ method (constructor) runs automatically when an object is created and is used to initialize attributes.
      • self refers to the instance itself within class methods.
      • Attributes are variables (data) associated with an object, accessed via object.attribute.
      • Methods are functions defined in a class that objects can call, accessed via object.method().

      Classes and objects allow you to bundle related data and functionality together, creating modular and organized code that models concepts effectively.

      Continue Learning

      Python Variables

      Popular

      Getting Started: Understanding Variables in Python In programming, we often need to store informatio

      Python Functions Scope

      For You

      Where Variables Live: Understanding Scope In Python, not all variables are accessible from every par

      Python Input-Output

      For You

      Talking to Your Program: Understanding Inputs and Outputs Programs often need to interact with the w

      Personalized Recommendations

      Log in to get more relevant recommendations based on your reading history.