Python Classes: Create Objects, Add Methods, Understand State
In this article
Python classes are the foundation of object-oriented programming (OOP) in the language. A class is a blueprint for creating objects—self-contained units that bundle data (attributes) with the functions that operate on that data (methods). When you create an object from a class, you get an instance with its own distinct state, meaning the values stored in its attributes can differ from those of other instances. This article explains how classes work, how to define and use them, and what "state" really means in practice.
What Is a Class and Why Use One?
A class defines a new data type. It groups related data and behavior into a single, reusable structure. Instead of juggling separate variables and functions, you create a class that encapsulates both. For example, a BankAccount class might have attributes like owner and balance, and methods like deposit() and withdraw(). This makes code more organized, easier to debug, and promotes reusability.
Classes also enable inheritance, where a new class can reuse and extend the behavior of an existing one. This mirrors real-world relationships (a Dog is a kind of Animal) and reduces duplication. While Python supports functional programming, classes are the standard way to model complex systems with interacting parts.
Creating a Class and Instantiating Objects
To define a class, use the class keyword followed by a name (by convention, in CamelCase). Inside, you define methods—functions that belong to the class. The special __init__ method is the constructor; it runs automatically when you create a new instance and typically sets up the initial state.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")To create an object, you call the class like a function, passing arguments that __init__ expects:
my_dog = Dog("Rex", 3)
my_dog.bark() # Output: Rex says woof!The variable my_dog is an instance of Dog. Each instance has its own copy of the attributes, so you can have many dogs with different names and ages. The self parameter in methods refers to the specific instance being used—it is how the method accesses that instance's data.
Adding Methods: Instance, Class, and Static
Methods are functions defined inside a class. There are three main types:
- Instance methods (the most common) take
selfas the first parameter and can access and modify the instance's attributes. - Class methods take
cls(the class itself) and are decorated with@classmethod. They can access class-level attributes but not instance-specific data. - Static methods are decorated with
@staticmethodand do not receiveselforcls. They behave like plain functions but are logically grouped with the class.
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self): # instance method
print(f"{self.name} says woof!")
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def is_domesticated():
return TrueClass attributes (like species) are shared by all instances, while instance attributes (like name) are unique to each object. This distinction is key to understanding state.
Understanding Object State
State refers to the current values of an object's attributes. When you create an instance, it gets its own namespace (a dictionary called __dict__) that stores its attributes. Changing one object's attribute does not affect another, unless the attribute is a class attribute (shared) or a mutable object that is passed by reference.
dog1 = Dog("Rex", 3)
dog2 = Dog("Buddy", 5)
dog1.age = 4 # only dog1's age changes
print(dog2.age) # still 5State is dynamic: methods can modify it. For instance, a deposit() method can update the balance attribute. This is the core of OOP—objects are not just data containers; they are active entities that manage their own state through methods.
A common pitfall is using a mutable default argument in a method definition. This creates a shared object that all calls reuse, leading to unexpected state leakage. Always use None as a default and create a new object inside the method.
Common Mistakes and Misconceptions
- Forgetting
self: Instance methods must takeselfas the first parameter; otherwise, calling the method raises a TypeError. - Confusing class and instance attributes: If you assign to an attribute name in
__init__, you create an instance attribute that shadows the class attribute. If you mutate a class attribute (like a list) through one instance, the change is visible to all instances. - Using mutable default arguments: As mentioned, this causes shared state. Use
Noneand initialize inside the method. - Thinking
selfis a keyword: It is just a convention; you could name itthis, but the first parameter always refers to the instance.
Comparing Classes to Other Approaches
Classes are one of several ways to structure code. Dictionaries can hold data, and functions can operate on them, but they lack encapsulation and built-in behavior. Namedtuples and dataclasses (in Python 3.7+) provide lightweight alternatives for simple data containers, but they don't offer methods or inheritance in the same way. Classes are the right choice when you need to model entities with both data and behavior, especially when you plan to use inheritance or polymorphism.
Best Practices for Designing Classes
- Keep classes focused: Each class should represent one concept or responsibility.
- Use descriptive names: Class names in
CamelCase, methods and attributes insnake_case. - Encapsulate internal details: Prefix attributes with an underscore (e.g.,
_balance) to signal they are private, and provide getter/setter methods if needed. - Override
__repr__: This gives a readable string representation, which aids debugging. - Prefer composition over inheritance: Often, combining simpler classes is more flexible than deep inheritance hierarchies.
Frequently Asked Questions
What is the difference between a class and an instance?
A class is the blueprint; an instance is a concrete object created from that blueprint. The class defines attributes and methods, while the instance holds actual data. For example, Dog is the class, and my_dog is an instance of Dog.
Why do I need self in every method?
self is how the method knows which instance it is working with. When you call my_dog.bark(), Python automatically passes my_dog as the first argument, which is assigned to self. Without it, the method would have no way to access the instance's attributes.
Can I change an object's state after it is created?
Yes. You can assign new values to its attributes at any time, either directly (e.g., obj.attr = value) or through methods. This is a fundamental feature of mutable objects in Python.
What is the difference between @classmethod and @staticmethod?
A class method receives the class as the first argument (cls) and can access class-level attributes or create instances. A static method receives no automatic arguments; it is just a function that happens to live inside the class. Use class methods when you need to refer to the class itself, and static methods for utility functions that don't depend on class or instance data.
How do I create a class that cannot be modified after creation?
You can override __setattr__ to raise an exception after initialization, or use a namedtuple or dataclass with frozen=True. For example, @dataclass(frozen=True) makes instances immutable.
What is the best way to learn classes?
Start with simple, real-world examples: a Car, a Student, or a BankAccount. Write methods that change state and observe how each instance behaves independently. Then move on to inheritance and polymorphism. Practice is more effective than reading alone.