Class Creation and Instantiation
Overview
A class is a blueprint for creating objects, defining their structure and behavior. When you instantiate a class, you create a unique object (instance) in memory based on that blueprint. Think of a class as a cookie cutter, and the objects as the cookies themselves. class Server: def __init__(self, host): self.host = host app = Server('localhost') In Python, variables are labels, and objects are boxes. Instantiation creates a new box in memory. The `self` parameter inside `__init__` is a temporary label pointing to that newly created box during setup. Each instance encapsulates its own independent state. The class itself remains the shared blueprint. class BrokenServer: def __init__(self): return "Ready" # Trap: __init__ must return None s = BrokenServer() # Raises TypeError The `__init__` method is strictly for initialization and cannot return a value. Attempting to return anything other than `None` raises a `TypeError` at instantiation. The mechanics of `self` and class functions are covered fully in instance-methods.
Classes allow you to group related data and functions together into a single, cohesive unit, making complex code organized and reusable.
Where used: `FastAPI` dependency injection, `Pydantic` data models, Database ORMs
Why learn this
- Grouping state and behavior for complex applications
- Understanding how third-party libraries structure their APIs
Code walkthrough
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
app_server = Server('localhost', 8080)
print(app_server.port)
Focus: app_server = Server('localhost', 8080)
Aha moment
class Config:
tags = []
c1 = Config()
c2 = Config()
c1.tags.append('prod')
print(c2.tags)
Prediction: What does `c2.tags` print?
Common guess: `[]`
Variables defined directly in the class body are class attributes, shared by all instances. To give each instance its own list, initialize it inside `__init__` using `self.tags = []`.
Common mistakes
- Forgetting `self` in `__init__`: Python automatically passes the instance as the first argument to instance methods. Forgetting `self` causes a `TypeError` when creating the object.
- Modifying class attributes instead of instance attributes: Defining variables outside `__init__` makes them class-level, shared across all instances. Always initialize instance-specific data inside `__init__`.
Glossary
- instantiate
- The process of creating a specific object from a class blueprint, e.g. `user = User('alice')`.
- instance
- A unique, individual object created from a class blueprint, e.g. `user` in `user = User('alice')` is an instance of `User`.
Recall questions
- What is the difference between a class and an instance?
- What does instantiation do in memory?
- What happens if you return a value from `__init__`?
Understanding checks
What will this code print?
`False`
Each time a class is instantiated, a new unique object (box) is created in memory. `s1` and `s2` are labels pointing to different boxes, each with its own `port` value.
A developer thinks that calling `Server(8000)` merely modifies a global `Server` object. What's wrong with this mental model?
The class is a blueprint (cookie cutter), not the object itself. Instantiation creates a brand new unique object (cookie) in memory every time it's called.
Understanding that classes are blueprints and instantiation allocates new memory is crucial to understanding object-oriented programming in Python.
Practice tasks
Modify User Class Initialization
The `User` class currently only accepts and stores a `username`. Modify the `__init__` method so it also accepts an `email` parameter and saves it as an instance attribute. Then, update the instantiation call to pass an email.
Challenge
Database Connection Simulation
Create a `DatabaseConnection` class. The `__init__` method should take a `database_url`. It should also initialize an `is_connected` attribute to `False`. Then, instantiate the class with `'postgresql://localhost/mydb'` and print the `is_connected` attribute.
Continue learning
Previous: Defining functions and return values