Lesson 16 of 52Objects
Classes and Objects
Bundle data and behaviour into your own types with classes, properties, classmethods and staticmethods.
Every serious Python codebase is built from classes: Django models, FastAPI's Pydantic schemas, pytest fixtures, the requests.Session you call every day. A class lets you invent your own type, with its own data and its own behaviour, so the rest of your code can talk in terms of Order and Invoice instead of loose dicts and lists. In the Functions unit you bundled behaviour; a class bundles behaviour together with the data it works on.
A class is a blueprint, an object is a thing built from it
A class describes what a kind of thing looks like and what it can do. An object (also called an instance) is one concrete thing made from that class. str is a class; "hello" is an instance of it. You have been using objects all along.
You define a class with the class keyword and create an instance by calling the class like a function.
Press Run (⌘ Enter) to see what happens.Dog is the blueprint. rex and luna are two separate objects, each carrying its own name and age. Values stored on an object are called attributes. Functions defined inside a class are called methods.
a = Dog('A', 1) and b = Dog('B', 2), how many Dog classes and how many Dog objects exist?__init__ and self
When you write Dog("Rex", 3), Python does two things. It creates a new, empty object, then it calls __init__ on it, passing the new object as the first argument. That first argument is always called self by convention. It is the object being set up.
So self.name = name means "store name on this particular dog". Inside any method, self is how you reach the object the method was called on. In fact rex.bark() is just a shortcut for Dog.bark(rex).
Press Run (⌘ Enter) to see what happens.__init__ is not a constructor in the C++ or Java sense: the object already exists when it runs. It is an initialiser. It should return nothing.
What does this print?
class Box:
def __init__(self, items):
self.items = items
def add(self, item):
self.items.append(item)
b = Box([])
b.add("pen")
b.add("cup")
print(len(b.items))t.start() on this class?class Timer:
def start():
print("go")Class attributes vs instance attributes
Attributes assigned on self live on one instance. Attributes assigned directly in the class body live on the class and are shared by every instance. When you read obj.x, Python looks on the instance first, then on the class.
Class attributes are great for constants like species = "dog". They are a trap when the value is mutable, like a list.
members is created once, when the class body runs. It belongs to the class.
Press Run (⌘ Enter) to see what happens.Note the difference in the last lines. Assigning b.sport = ... creates a new instance attribute that hides the class one. Mutating a.members.append(...) changes the shared object in place.
What does this print?
class Player:
count = 0
def __init__(self, name):
self.name = name
Player.count += 1
Player("Sam")
Player("Leo")
p = Player("Priya")
print(p.count)Properties: attributes with logic
Sometimes an attribute should be computed, or validated on assignment. In Java you would write getX() and setX(). In Python you start with a plain attribute, and if you later need logic you turn it into a property without changing any calling code.
Press Run (⌘ Enter) to see what happens.@property turns a method into a read-only attribute. @width.setter adds the code that runs on assignment. The real value lives in self._width. Even self.width = width inside __init__ goes through the setter, so validation happens from the start.
@classmethod and @staticmethod
A regular method receives the instance (self). Two decorators change that:
@classmethodreceives the class ascls. Its main use is an alternative constructor: another way to build an instance, likedatetime.fromtimestamp(...)ordict.fromkeys(...).@staticmethodreceives nothing automatically. It is a plain function that lives in the class because it belongs there logically.
Press Run (⌘ Enter) to see what happens.Using cls(...) instead of Temperature(...) matters: if someone subclasses Temperature, from_fahrenheit builds the subclass.
Match each method kind to what it receives first.
Encapsulation by convention
Python has no private keyword. Instead it relies on naming conventions that every Python developer respects:
| Name | Meaning |
|---|---|
balance | Public. Part of the class's interface. |
_balance | Internal. "Please do not touch from outside." Nothing stops you, but linters and reviewers will. |
__balance | Name mangling. Python renames it to _Account__balance so subclasses cannot clash with it by accident. |
Press Run (⌘ Enter) to see what happens.Double underscores are not security. They exist to avoid name collisions in inheritance. Use a single _ for "internal" in everyday code.
class Vault, you write self.__key = 1. What attribute name does the object actually get?Build a Stack class
Write a class Stack that stores items last-in, first-out.
push(item)adds an item on top.pop()removes and returns the top item. If the stack is empty, returnNone.peek()returns the top item without removing it (orNonewhen empty).is_empty()returnsTrueorFalse.size()returns how many items are stored.
s = Stack()
s.push(1); s.push(2)
s.peek() # 2
s.pop() # 2
s.size() # 1Each Stack must have its own storage: two stacks must never share items.
Temperature with a property
Write a class Temperature that stores a temperature in Celsius.
Temperature(c)storescin the attributecelsius.fahrenheitis a property: reading it returnscelsius * 9 / 5 + 32, and assigning to it updatescelsius.Temperature.from_fahrenheit(f)is a classmethod that builds aTemperaturefrom a Fahrenheit value.Temperature.is_valid(c)is a staticmethod that returnsFalseifcis below absolute zero (-273.15), elseTrue.
t = Temperature(100)
t.fahrenheit # 212.0
t.fahrenheit = 32
t.celsius # 0.0
Temperature.from_fahrenheit(-40).celsius # -40.0- instance
- One concrete object built from a class.
Dog("Rex", 3)returns an instance ofDog. - self
- The first parameter of a regular method: the instance the method was called on.
- class attribute
- A value defined in the class body and shared by every instance. Dangerous when mutable.
- @property
- Turns a method into something you read like an attribute, with optional setter logic.
- @classmethod
- A method that receives the class as
cls; the standard way to write alternative constructors. - name mangling
- Python renames
__xinside classCto_C__xto avoid clashes in subclasses.