Classes & Objects — Python

class Menu: is the template, and Menu("coffee with milk", 15) makes an object (instance) from it: one finished thing with its own data. __init__ is the…

So far, one menu item has been stored as a pair: a name and a price. The formula for its total is in a separate function, somewhere else. When each item needs more, such as stock or its own way to calculate a total, the data and the functions become scattered.

A class puts that data and those functions in one place. Look at the blank menu card at Mr. Darto's stall: every card has the same fields, "Name: ___" and "Price: ___". The blank card is designed once, then each card is filled in separately. One becomes the coffee with milk card at $15, another the sweet tea card at $5. In code, the blank card is the class: a template for making objects. Each filled-in card is an object: one finished thing made from that template.

Making a class and objects

Here is that blank menu card as code, then two cards filled in from it:

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

    def total(self, quantity):
        return self.price * quantity

coffee = Menu("coffee with milk", 15)
tea = Menu("sweet tea", 5)

print(coffee.name)      # coffee with milk
print(coffee.total(3))  # 45
print(tea.total(4))     # 20

__init__ and self

__init__ is a special method that Python runs automatically every time a new object is made. Its job is to fill in that object's first attributes. A method like this is called a constructor. Here is what happens when Python runs coffee = Menu("coffee with milk", 15):

Step What happens
1 Python makes a new, empty Menu object
2 Python calls __init__ with self = that new object, name = "coffee with milk", price = 15
3 self.name = name and self.price = price attach two attributes to that object
4 The filled-in object is given to the variable coffee

Python fills in self. So Menu("coffee with milk") is missing only one argument, price, even though __init__ has three parameters:

Traceback (most recent call last):
  File "/home/darto/stall.py", line 9, in <module>
    coffee = Menu("coffee with milk")
TypeError: Menu.__init__() missing 1 required positional argument: 'price'

Methods that change attributes

A method may change its own object's attributes. The Order class records the total bill of one table. This code continues stall.py above, and goes below the Menu class. So coffee and tea, made earlier, can still be used:

toast = Menu("toast", 12)

class Order:
    def __init__(self, table):
        self.table = table
        self.total = 0

    def add(self, menu, quantity):
        self.total = self.total + menu.price * quantity
        print(self.total)

    def cancel(self, menu, quantity):
        cut = menu.price * quantity
        if cut > self.total:
            print("Can't cancel that")
        else:
            self.total = self.total - cut
            print(self.total)

order = Order(5)
order.add(coffee, 3)   # 45
order.add(tea, 4)      # 65
order.add(toast, 2)    # 89
order.cancel(tea, 30)  # Can't cancel that

Object attributes and class attributes

A variable written directly in the class body (inside the class, outside the methods), not through self., is a class attribute. There is only one, and every object shares it. An attribute made through self., such as self.name, is an object attribute: each object has its own. This code shows what happens when a list is made a class attribute:

class Order:
    item = []

    def __init__(self, table):
        self.table = table

    def add(self, name):
        self.item.append(name)

a = Order(1)
b = Order(2)
a.add("coffee with milk")
b.add("sweet tea")
print(a.item)   # ['coffee with milk', 'sweet tea']
print(b.item)   # ['coffee with milk', 'sweet tea']

__str__, __repr__ and __len__

A method whose name starts and ends with two underscores, like __init__, is called a dunder method (double underscore). Python calls it by itself in certain situations. Without __str__, print(coffee) only shows the class name and its memory address: <__main__.Menu object at 0x1027ddd30> (the address is different on every run). The class below adds __str__ and __repr__:

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

    def __str__(self):
        return f"{self.name} ({self.price})"

    def __repr__(self):
        return f"Menu('{self.name}', {self.price})"

coffee = Menu("coffee with milk", 15)
tea = Menu("sweet tea", 5)
print(coffee)          # coffee with milk (15)
print(repr(coffee))    # Menu('coffee with milk', 15)
print([coffee, tea])   # [Menu('coffee with milk', 15), Menu('sweet tea', 5)]

You don't always have to write __init__ and __repr__ yourself. When __init__ only copies parameters into attributes, @dataclass from the built-in dataclasses module can write both for you. The @dataclass line above the class is called a decorator: it adds __init__ and __repr__, and makes == compare the attributes' values.

from dataclasses import dataclass

@dataclass
class Menu:
    name: str
    price: int

coffee = Menu("coffee with milk", 15)
print(coffee)                                     # Menu(name='coffee with milk', price=15)
print(coffee == Menu("coffee with milk", 15))     # True

⚠️ A forgotten self and a misspelt __init__

TL;DR: class Menu: is the template, and Menu("coffee with milk", 15) makes an object (instance) from it: one finished thing with its own data. __init__ is the constructor: a method that runs automatically when an object is made, and fills in its attributes (the variables that belong to the object) through self.name = name. self is the object being worked on. Python fills it in, so Menu("coffee with milk") is missing only one argument: missing 1 required positional argument: 'price'. A method is a function inside a class, always with self as its first parameter, and it may change attributes (self.total = self.total + ...). A class attribute (a variable written in the class body, outside the methods) is shared by every object, so a list that belongs to each object is made in __init__. Python calls dunder methods (names with two underscores on each side) by itself: __str__ for print (users), __repr__ for developers and for list contents, __len__ for len().

⚡ The template and the finished item

Write:

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

    def total(self, quantity):
        return self.price * quantity

coffee = Menu("coffee with milk", 15)
tea = Menu("sweet tea", 5)

print(coffee.name)      # coffee with milk
print(coffee.total(3))  # 45
print(tea.total(4))     # 20

Meaning: class Menu: is the template, and Menu("coffee with milk", 15) makes an object from it. coffee.name reads the attribute name, a variable that belongs to the object coffee. coffee.total(3) calls a method, a function inside the class, with the price of coffee. coffee and tea come from the same class, but their attributes are separate.

⚡ __init__ and self

Guess first: __init__ has three parameters. How many arguments is Menu("coffee with milk") missing?

Only one, price. Python fills in the self parameter by itself.

Meaning: __init__ is the constructor: it runs automatically every time a new object is made, to fill in its attributes. self is the object being worked on (in coffee.total(3), self is coffee), and it's always the first parameter of every method.

⚡ An attribute everyone shares

Guess first: item = [] is written in the class body, not in __init__. Table 1 adds coffee with milk, table 2 adds sweet tea. What does table 1's a.item hold?

['coffee with milk', 'sweet tea']. Both tables write to the same list.

Meaning: A variable in the class body (inside the class, outside the methods) is a class attribute: there's only one, shared by every object. A list that belongs to each object is made in __init__: self.item = [].

⚡ A print that reads well

Meaning: Without __str__, print(coffee) only writes <__main__.Menu object at 0x...>. __str__ returns text for users, __repr__ for developers and for list contents.

What you will learn