Skip to content

Lesson 16 of 52Objects

Classes and Objects

Bundle data and behaviour into your own types with classes, properties, classmethods and staticmethods.

16 min read0/6 questions

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.

Python
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): return f"{self.name} says woof" rex = Dog("Rex", 3)luna = Dog("Luna", 5) print(rex.bark())print(luna.name, luna.age)print(type(rex))print(isinstance(luna, Dog))
Output
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.

Quick check
After a = Dog('A', 1) and b = Dog('B', 2), how many Dog classes and how many Dog objects exist?
Need a nudge? A hint rules out a wrong answer.

__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).

Python
class Counter: def __init__(self, start=0): self.value = start def increment(self, by=1): self.value += by return self.value c = Counter()c.increment()c.increment(5)print(c.value) # The method call is sugar for calling the function on the class:Counter.increment(c)print(c.value)
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.
Quick check
What happens when you call t.start() on this class?
class Timer:
  def start():
      print("go")
Need a nudge? A hint rules out a wrong answer.

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.

The shared-list trap
class Team:
    members = []
NamesObjects in memoryTeam.memberslist[]

members is created once, when the class body runs. It belongs to the class.

1/4
Python
class Team: members = [] # shared by every Team (the bug) sport = "football" # shared constant (fine, strings are immutable) a, b = Team(), Team()a.members.append("Ada")print(b.members) b.sport = "chess" # assignment creates an attribute on b onlyprint(a.sport, b.sport, Team.sport)
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Python
class Rectangle: def __init__(self, width, height): self.width = width self.height = height @property def area(self): return self.width * self.height @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError("width must be positive") self._width = value r = Rectangle(3, 4)print(r.area) # no parentheses: it reads like an attributer.width = 10print(r.area)try: r.width = -1except ValueError as e: print("rejected:", e)
Output
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:

  • @classmethod receives the class as cls. Its main use is an alternative constructor: another way to build an instance, like datetime.fromtimestamp(...) or dict.fromkeys(...).
  • @staticmethod receives nothing automatically. It is a plain function that lives in the class because it belongs there logically.
Python
class Temperature: def __init__(self, celsius): self.celsius = celsius @classmethod def from_fahrenheit(cls, f): return cls((f - 32) * 5 / 9) @staticmethod def is_freezing(celsius): return celsius <= 0 t = Temperature.from_fahrenheit(212)print(t.celsius)print(Temperature.is_freezing(-3))
Output
Press Run (⌘ Enter) to see what happens.

Using cls(...) instead of Temperature(...) matters: if someone subclasses Temperature, from_fahrenheit builds the subclass.

Match the pairs0/4 matched

Match each method kind to what it receives first.

Choose an item, then its match on the other side.

Encapsulation by convention

Python has no private keyword. Instead it relies on naming conventions that every Python developer respects:

NameMeaning
balancePublic. Part of the class's interface.
_balanceInternal. "Please do not touch from outside." Nothing stops you, but linters and reviewers will.
__balanceName mangling. Python renames it to _Account__balance so subclasses cannot clash with it by accident.
Python
class Account: def __init__(self): self._audit = [] # internal, by convention self.__pin = "1234" # mangled a = Account()print(a._audit)print(hasattr(a, "__pin"))print(a._Account__pin) # still reachable, just renamed
Output
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.

Quick check
Inside class Vault, you write self.__key = 1. What attribute name does the object actually get?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

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, return None.
  • peek() returns the top item without removing it (or None when empty).
  • is_empty() returns True or False.
  • size() returns how many items are stored.
s = Stack()
s.push(1); s.push(2)
s.peek()   # 2
s.pop()    # 2
s.size()   # 1

Each Stack must have its own storage: two stacks must never share items.

Python
class Stack: def __init__(self) -> None: # Create the storage for this stack here. pass def push(self, item) -> None: pass def pop(self): pass def peek(self): pass def is_empty(self) -> bool: pass def size(self) -> int: pass
ChallengeMedium

Temperature with a property

Write a class Temperature that stores a temperature in Celsius.

  • Temperature(c) stores c in the attribute celsius.
  • fahrenheit is a property: reading it returns celsius * 9 / 5 + 32, and assigning to it updates celsius.
  • Temperature.from_fahrenheit(f) is a classmethod that builds a Temperature from a Fahrenheit value.
  • Temperature.is_valid(c) is a staticmethod that returns False if c is below absolute zero (-273.15), else True.
t = Temperature(100)
t.fahrenheit          # 212.0
t.fahrenheit = 32
t.celsius             # 0.0
Temperature.from_fahrenheit(-40).celsius   # -40.0
Python
class Temperature: def __init__(self, celsius: float) -> None: pass # Add a fahrenheit property (with a setter), # a from_fahrenheit classmethod and an is_valid staticmethod.
Key terms
instance
One concrete object built from a class. Dog("Rex", 3) returns an instance of Dog.
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 __x inside class C to _C__x to avoid clashes in subclasses.