Skip to content
Visual explainer 4h to learn 5 steps

Classes, objects & methods

Design a class with an initialiser, attributes and methods for a small domain.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 18 of 34

In short

A class is a blueprint that bundles data (attributes) with behaviour (methods). Each object created from it is an instance with its own attribute values, set up by the __init__ method.

Think of it like this: A class is a cookie cutter; each cookie is an instance with its own decorations.

Explained simply

So far you have kept data in lists and dicts and written separate functions to work on it. That works, but as a program grows you end up passing the same dict into ten functions and hoping nobody misspells a key. A class lets you put the data and the functions that change it in one place.

Think of a class as a form with blank boxes, and each object as one filled-in copy of that form. The class Account says every account has an owner and a balance. Account("Ana", 50) fills in one copy. Account("Bo", 200) fills in another. They follow the same rules but keep their own numbers.

A method is just a function that lives inside the class. When you write acct.deposit(10), Python quietly passes acct in as the first argument, which by convention is called self. That is how the method knows which account to change.

You do not need classes for everything. A small script with a few functions is often clearer. Reach for a class when you have a thing with state (data that changes over time) and several actions that belong to that thing, like a bank account, a shopping cart or a game character.

Press Play on a diagram to walk through it one step at a time.

FlowWhat happens on Account("Ana", 50)
  1. Step 1
    Call the class

    Account("Ana", 50) looks like a function call

  2. Step 2
    New empty object

    Python creates a fresh instance

  3. Step 3
    __init__ runs

    self is the new object; set self.owner, self.balance

  4. Step 4
    Instance returned

    Assigned to a variable, ready for methods

MapOne class, many instances
class Account
  • acct1
    • owner = "Ana"
    • balance = 50
  • acct2
    • owner = "Bo"
    • balance = 200
  • Shared methods
    • deposit()
    • withdraw()
CompareDict plus functions vs a class
Dict + functions
  • acct = {"owner": "Ana", "balance": 50}
  • deposit(acct, 10)
  • Typos in keys fail late
  • Rules spread across files
Class
  • acct = Account("Ana", 50)
  • acct.deposit(10)
  • Typos raise AttributeError
  • Rules live next to the data
MapModelling a small library system
Library domain
  • Book
    • title, author, isbn
    • is_available()
  • Member
    • name, borrowed list
    • can_borrow()
  • Library
    • books, members
    • lend(book, member)
    • give_back(book)

In depth

What self really is

There is no magic in self. When you write a.deposit(25), Python looks up deposit on the class and calls Account.deposit(a, 25). The object before the dot becomes the first argument. You could write that longer form yourself and it would work the same way.

The name self is only a convention, but every Python programmer expects it, so always use it. If you forget it in the parameter list, you get an error like TypeError: deposit() takes 1 positional argument but 2 were given, because Python still passes the object in. Inside a method, you must write self.balance, not just balance. A bare name is a local variable that disappears when the method returns.

  • a.deposit(25) is the same as Account.deposit(a, 25)
  • a.deposit without () is a bound method you can store and call later
  • Forgetting self in def gives a 'takes N positional arguments' TypeError

How Python finds an attribute

Every instance stores its own attributes in a dict you can see with vars(a) or a.__dict__. When you read a.bank, Python first looks in the instance's dict. If the name is not there, it looks in the class, then in parent classes. If nothing is found, you get AttributeError.

Assignment works differently. a.bank = "Other" always writes into the instance's own dict. It does not change the class attribute; it creates a new instance attribute that hides (shadows) the class one for that object only. Other instances still see the class value. To change the shared value for everyone, assign to the class: Account.bank = "Other".

FlowReading a.bank, step by step
  1. Step 1
    Instance dict

    Is 'bank' in vars(a)? Use it

  2. Step 2
    Class

    Else look in Account

  3. Step 3
    Parent classes

    Else follow the inheritance chain

  4. Step 4
    AttributeError

    Nothing found anywhere

The shared mutable class attribute trap

Class attributes are fine for values that never change per object, like a constant rate or a bank name. They are a trap for lists and dicts. If you write history = [] at class level and then self.history.append(x) in a method, every instance appends to the same single list, because append changes the list in place and never creates an instance attribute.

The fix is simple: create mutable values inside __init__, so each object gets its own. Use class attributes only for shared constants or for things you really want shared, like a counter of how many objects were created (and then update it through the class name).

  • Shared constant: RATE = 0.02 at class level is fine
  • Per-object list: self.history = [] inside __init__
  • Count instances with Account.count += 1, not self.count += 1

Keeping objects valid: properties and naming

Python has no private keyword. Instead, a single leading underscore, like self._balance, tells other programmers: this is internal, do not touch it from outside. A double underscore, self.__pin, triggers name mangling: Python renames it to _Account__pin to avoid clashes in subclasses. It is not real security.

To control access, use @property. A property looks like a normal attribute from outside (acct.balance) but runs a method. Add a setter with @balance.setter to validate new values, for example raise ValueError on a negative balance. This lets you start with a plain attribute and add checks later without changing any code that uses the class.

Three kinds of methods

A normal method takes self and works on one instance. A @classmethod takes cls (the class itself) instead. Its most common use is an alternative constructor: Account.from_dict(data) reads a dict and returns cls(data["owner"], data["balance"]). Because it uses cls, it also works correctly for subclasses.

A @staticmethod takes neither self nor cls. It is just a plain function placed in the class because it belongs there logically, like a helper that checks whether an IBAN string looks valid. If a static method does not really relate to the class, a module-level function is usually simpler.

  • def deposit(self, amt): works on one object
  • @classmethod def from_dict(cls, d): builds objects
  • @staticmethod def is_valid(code): needs no object at all

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Define a class with __init__~50m
  2. 2
    Add attributes and methods~50m
  3. 3
    Create and use several instances~50m
  4. 4
    Use class vs instance attributes~50m
  5. 5
    Model a small domain with classes~50m

Key points

  • Methods are functions defined in a class; their first parameter is self.
  • Instance attributes (self.x) belong to one object; class attributes are shared by all.
  • Call methods on an instance: acct.deposit(10) passes acct as self.
  • Use classes when data and the operations on it naturally belong together.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
class Account:
    bank = "Invicly Bank"          # class attribute, shared

    def __init__(self, owner, balance=0):
        self.owner = owner           # instance attributes
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

a = Account("Ana", 50)
b = Account("Bo")
a.deposit(25)
print(a.balance, b.balance, a.bank)  # 75 0 Invicly Bank

A bank account that refuses bad withdrawals

Step 1: store the owner and balance in __init__, with a separate history list per object. Step 2: deposit checks that the amount is positive. Step 3: withdraw refuses to go below zero by raising ValueError, so the account can never be in an invalid state. Step 4: every successful change is logged in history, so you can later show a statement.

python
class Account:
    def __init__(self, owner, balance=0):
        self.owner, self.balance = owner, balance
        self.history = []          # one list per account

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.balance += amount
        self.history.append(("deposit", amount))
    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount
        self.history.append(("withdraw", amount))

Modelling a shopping cart with two classes

Nouns in the problem become classes (Product, Cart) and verbs become methods (add, total). Step 1: Product holds a name and a price. Step 2: Cart holds a dict mapping product to quantity. Step 3: total() adds price times quantity for each line. Note that Cart does not copy prices; it asks each Product, so a price change shows up everywhere.

python
class Product:
    def __init__(self, name, price):
        self.name, self.price = name, price

class Cart:
    def __init__(self):
        self.lines = {}            # Product -> quantity
    def add(self, product, qty=1):
        self.lines[product] = self.lines.get(product, 0) + qty
    def total(self):
        return sum(p.price * q for p, q in self.lines.items())

pen = Product("pen", 1.5)
cart = Cart(); cart.add(pen, 4); cart.add(Product("pad", 3))
print(cart.total())   # 9.0

Quick reference

  • obj.method(x) is shorthand for Class.method(obj, x)
  • vars(obj) shows an instance's own attributes as a dict
  • Create lists and dicts in __init__, never as class attributes
  • self._name means internal by convention; Python does not enforce it
  • @property lets you add validation without changing how callers use the attribute
  • @classmethod def from_x(cls, ...): return cls(...) is the usual alternative constructor
  • isinstance(obj, Account) checks the type, including subclasses

Common mistakes

  • Forgetting self as the first method parameter.
  • Storing a mutable list as a class attribute, so all instances share it.
  • Making a class for something that is just one function.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Account has class attribute bank = "A". You run a.bank = "B". What does Account("Bo").bank return?

Question 2

2A class has items = [] at class level and methods call self.items.append(x). What happens with two instances?

Question 3

3What is the main use of @classmethod?

Question 4

4You defined def area(): inside a class and call r.area(). What error do you get?

Question 5

5Inside a method you write balance = 100 instead of self.balance = 100. What happens?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a Counter class with a value that starts at 0, an increment() method and a reset() method. Create two counters and show that they count independently.

  2. Exercise 2medium

    Write a Temperature class that stores Celsius and has a fahrenheit property. Setting celsius below -273.15 must raise ValueError.

  3. Exercise 3hard

    Model a tiny library: Book (title, available flag) and Library (list of books) with lend(title) that marks a book unavailable, raising LookupError if it is missing and ValueError if it is already lent. Add a classmethod Library.from_titles(list_of_titles).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I always need __init__?
No. If a class has no per-object data to set up, Python uses a default initialiser. But most classes that hold data define one.
What is the difference between a function and a method?
A method is a function defined inside a class. When called on an instance, the instance is passed in automatically as self.
Does Python have private attributes?
Not truly. A leading underscore marks a name as internal by convention, and a double underscore only renames it. Anyone can still reach it.
When should I not use a class?
When you only have one function, or data that never changes and has no behaviour. A function or a dict is simpler there, and a dataclass fits plain records.

Go deeper

ShareXLinkedInWhatsApp