20.1 Classes and OOP
Model state and behavior when they belong together.
Before you start
Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.
Core concepts
A class defines a type; an instance holds its own state. __init__ initializes an instance, and instance methods receive that instance as self. Prefer functions for simple transformations; use a class when related operations share meaningful state.
An instance attribute belongs to one object. A mutable class attribute is shared, which can surprise you. Composition builds an object from other objects; inheritance specializes a type and should preserve the parent’s expected behavior.
Worked example
class Server:
def __init__(self, name, status):
self.name = name
self.status = status
def is_healthy(self):
return self.status == "healthy"
server = Server("web-01", "healthy")
print(server.is_healthy())
Mini lab
Create two Server objects. Change only the first status to critical. The second must remain healthy.
Hint
Start with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.Show a solution
class Server:
def __init__(self, name, status):
self.name = name
self.status = status
def is_healthy(self):
return self.status == "healthy"
first = Server("web-01", "healthy")
second = Server("web-02", "healthy")
first.status = "critical"
assert first.is_healthy() is False
assert second.is_healthy() is True
Knowledge check
When would you prefer a function over a class?
Check your answer
When an operation transforms input into output without maintaining shared state across calls.Common mistake
Do not introduce an inheritance hierarchy just to reuse a few lines. Start with small functions and composition.
Completion checklist
- Run the example and explain its output.
- Complete the mini lab without copying the solution.
- Test an edge case and explain how the code handles it.
- Answer the knowledge check in your own words.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form