By the end of this lesson, you will be able to define a Python class as a blueprint and create objects (instances) that hold their own data and behavior.
What it is
A class is a template or blueprint for creating objects. An object (or instance) is a specific realization of that class, containing its own unique data (attributes) and functions (methods). Think of a class as an architectural drawing for a house; each object is an actual house built from that drawing, with its own address and paint color.
Key terms include:
__init__: The constructor method that initializes new instances.self: A reference to the current instance, allowing access to its attributes.- Attributes: Variables bound to the object (data).
- Methods: Functions defined within the class (behavior).
Why it matters
- Encapsulation: Bundles data and logic together, hiding internal complexity.
- Reusability: Define structure once, create thousands of distinct instances.
- Organization: Groups related functionality, making code easier to navigate.
- State Management: Each object maintains its own state independently.
Syntax or steps
- Define a class using the
class ClassName:syntax. - Create an initializer method
def __init__(self, ...):. - Assign parameters to instance variables using
self.variable_name = value. - Define other methods that operate on
self. - Instantiate the class by calling it like a function:
obj = ClassName(args).
Example
class Dog:
def __init__(self, name, breed):
self.name = name # Instance attribute
self.breed = breed # Instance attribute
def bark(self):
return f"{self.name} says Woof!"
# Creating instances (objects)
d1 = Dog("Rex", "Labrador")
d2 = Dog("Buddy", "Golden Retriever")
print(d1.bark()) # Output: Rex says Woof!
print(d2.bark()) # Output: Buddy says Woof!
Explanation:
class Dog:defines the blueprint.__init__runs automatically whenDog(...)is called. It setsself.nameandself.breedfor that specific dog.d1andd2are separate objects. Changingd1.namedoes not affectd2.name.bark()usesself.nameto produce output specific to the instance calling it.
Common mistakes
- Forgetting
self: Methods must acceptselfas the first argument. Omitting it causes errors when calling the method on an instance. - Confusing Class vs. Instance Attributes: Assigning
x = 5inside the class body creates a shared class attribute. Useself.x = 5inside__init__for unique instance data. - Calling
__init__directly: Do not callobj.__init__(). Always instantiate viaClassName(), which handles initialization automatically. - Mutating Default Arguments: Avoid mutable defaults in
__init__(e.g.,def __init__(self, items=[])) as they are shared across instances.
When to use it
| Scenario | Use Classes/Objects | Use Functions/Dictionaries |
|---|---|---|
| Complex entities with state and behavior | Yes (e.g., User, BankAccount) | No |
| Simple data grouping | Maybe (overkill if no methods) | Yes (dicts/namedtuples) |
| Need inheritance/polymorphism | Yes | No |
Practice
Guided Exercise: Create a Car class with make and model attributes. Add a method describe() that returns a string like "Toyota Camry". Instantiate two cars and print their descriptions.
Challenge: Add a mileage attribute initialized to 0. Create a method drive(miles) that increases mileage. Ensure different car instances track mileage independently.
Quick check
Q: Why is self required in method definitions?
A: self refers to the specific instance calling the method, allowing access to its unique attributes and ensuring operations don't interfere with other instances.
Summary
Classes provide structure by bundling data and behavior into reusable blueprints. Objects are independent instances created from these classes, maintaining their own state through attributes accessed via self. Mastering this pattern is essential for writing scalable, organized Python applications.