Python Classes and Objects
In the beginning, writing code in Python is easy, but as your programs grow, keeping them organized becomes harder. You don’t just work with functions and variables – you start dealing with real-world things like users, products, orders, message, or files.
This is where classes come in. They let you group related data and actions (behavior) into a single structure, making your code easier to read, reusable, and easier to scale.
In this guide, you learn what Python classes are, how they work, and how to uses them effectively with practical examples.
What Is a Class in Python?
A class is a blueprint for creating objects. It defines:
- Attributes: data (what the object has)
- Methods: behavior (what the object can do)
What Is an Object in Python?
An object (instance) is a specific item created from that blueprint. A class is the template, and an object is the real thing created from it.
In simple terms:
- Class → Template
- Object → Actual item created from the template
Basic Syntax of a Class
class ClassName:
def __init__(self, value):
self.value = value
def method_name(self):
return self.value
Key Elements:
class → defines a new class
__init__() → is the constructor that runs automatically when an object is created
self → refers to the current object
Defining a Class
You can define a class in Python using a class keyword.
For example:
class Dog:
# The __init__ method (constructor) initializes a new instance
def __init__(self, name, age):
self.name = name # Instance attribute, unique to each instance
self.age = age # instance attribute, unique to each instance
# A method (instance function)
def bark(self):
return f"{self.name} says woof!"
In this code example, we define a class called Dog, which serves as a blueprint for creating dog objects.
The class also includes an __init__ method, known as the constructor, which is automatically called when a new Dog object is created. This method initializes instance attributes, name and age, which are unique to each individual dog. The self parameter is a reference to the current instance of the class – in our case, it refers to the specific dog object being created, so the method can give that dog its own name and age without affecting other dogs.
Additionally, the Dog class defines an instance method called bark, which represents a behavior of a dog. It uses the object’s name attribute to return a message showing that the dog is barking.
Note: An object and an instance usually mean the same thing in practice.
Creating and Using Objects
# Create two instances (objects) of the Dog class
d1 = Dog("Max", 2)
d2 = Dog("Bud", 4)
# Access instance attributes
print(f"Dog1 name: {d1.name}")
print(f"Dog2 name: {d2.name}")
# Calling the method
print(d1.bark())
print(d2.bark())
Output:
Dog1 name: Max
Dog2 name: Bud
Max says woof!
Bud says woof!
In this code example, we create two instances of Dog class named d1 and d2. The constructor (__init__) is called for each object, assigning "Max" and 2 to d1, and "Bud" and 4 to d2 as their respective name and age instance attributes.
Next, we access the instance attribute name using each object. Since instance attributes are unique to each object, d1.name and d2.name return different values corresponding to each dog. Similarly, you can access age attribute too.
Finally, the bark method is called on both d1 and d2. Each method call uses the object’s own name attribute, resulting in different output message for each dog, even though the same method definition is used.
Attributes in Python Classes
Attributes are variables that belong to the class or its instances. There are two types of attributes in Python classes:
- Instance Attributes
- Class Attributes
1. Instance Attributes
Instance attributes belong to a specific object and are usually defined inside __init__ method. They let each object have its own values, even if the objects come from the same class.
For example:
class Dog:
# The __init__ method (constructor) initializes a new instance
def __init__(self, name, age):
self.name = name # Instance attribute, unique to each instance
self.age = age # instance attribute, unique to each instance
# Create two instances (objects) of the Dog class
d1 = Dog("Max", 2)
d2 = Dog("Bud", 4)
# Access instance attributes
print(f"Dog1 name: {d1.name}")
print(f"Dog2 name: {d2.name}")
Output:
Dog1 name: Max
Dog2 name: Bud
In our Dog class, name and age are instance attributes. Each dog object can have different values for these attributes. In our case, the Dog object d1 has the name "Max" and age 2, while the Dog object d2 has name "Bud" and age 4.
Even though both objects are created from the same Dog class, each one stores its own value for these attributes. Changing the name or age of one dog does not affect the other.
2. Class Attributes
Class attributes belong to the class itself, not to any one object. They are defined directly inside the class, outside of the __init__ method. Their value is shared by all instances (objects) of that class.
For example:
class Dog:
# A class attribute, shared by all instances
species = "Canine"
# The __init__ method (constructor) initializes a new instance
def __init__(self, name, age):
self.name = name # Instance attribute, unique to each instance
self.age = age # instance attribute, unique to each instance
# Create two instances (objects) of the Dog class
d1 = Dog("Max", 2)
d2 = Dog("Bud", 4)
# Access class attribute (Recommended way)
print(f"Species (via class): {Dog.species}")
# Access class attribute (via instance)
print(f"Dog1 species: {d1.species}")
print(f"Dog2 species: {d2.species}")
Output:
Species (via class): Canine
Dog1 species: Canine
Dog2 species: Canine
In our Dog class, species is a class attribute shared by all dogs. Every Dog object can access this attribute, so Dog.species, d1.species, and d2.species all return the same value, "Canine".
Class attributes are useful for data that should be same for evey objects, such as category, type, or default setting.
Methods in Python Class
Methods are functions defined inside a class that describe what an object can do. They represent the behavior of an object and usually work with the object’s attributes.
They take self as their first parameter. The self keyword refers to the current object. It allows the method to access and modify the object’s attributes.
For example:
class Dog:
# The __init__ method (constructor) initializes a new instance
def __init__(self, name, age):
self.name = name # Instance attribute, unique to each instance
self.age = age # instance attribute, unique to each instance
# A method (instance function)
def bark(self):
return f"{self.name} says woof!"
# Create two instances (objects) of the Dog class
d1 = Dog("Max", 2)
d2 = Dog("Bud", 4)
print(d1.bark()) # Output: Max says woof!
In our example, bark is a method of the Dog class. When you call d1.bark(), Python automatically passes the object d1 as self, so the method knows which dog is barking.
The __init__() Method
The __init__() method is a special method in Python classes, often called the construtor. It runs automatically whenever a new object is created from a class and is used to set up (initialize) the object’s initial state.
This method is commonly used to define instance attributes, which store data unique to each object.
For example:
class Dog:
# The __init__ method (constructor) initializes a new instance
def __init__(self, name, age):
self.name = name # Instance attribute, unique to each instance
self.age = age # instance attribute, unique to each instance
When you create a new Dog object, Python automatically calls the __init__() method:
d1 = Dog("Max", 2)
Here, "Max" and 2 are passed as arguments to __init__() method, and the value are assigned to the d1 object’s name and age attributes.