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
class Menu:makes a new class calledMenu. Class names are written in PascalCase: a capital letter at the start of each word (Menu,DrinkMenu). Function names are different: they are written in snake_case (lowercase, with underscores between words).- A function written inside a class is called a method.
__init__andtotalare both methods. - The next section explains
__init__andself. For now:__init__fills in a new card, andselfis the card being filled in or read. Menu("coffee with milk", 15)makes a new object from that class. An object is also called an instance:coffeeis an instance ofMenu.coffee.namereads an attribute: a variable that belongs to an object, like the "Name" field on a card. Read the dot as "of":nameofcoffee.coffee.total(3)calls a method ofcoffee. The result is15 * 3, becauseself.priceinside it is the price ofcoffee.coffeeandteacome from the same class, but their attributes are separate.tea.total(4)uses the tea price, 5.
__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 |
selfis the object being worked on: the card being filled in or read. In Python,selfis written openly as the first parameter of every method. If you already know JavaScript:selfis likethisthere, which is not written as a parameter.- You never send
selfyourself. Python fills it in.coffee.total(3)really runs asMenu.total(coffee, 3):self=coffee,quantity= 3. - In
self.name = name, the left side is the object's attribute and the right side is the parameter that was sent. The names can be the same, but they are in different places.
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
self.total = 0in__init__: every new order starts at 0.self.total = self.total + ...reads this object's old total, adds to it, then stores the result on the same object again. The short form isself.total += menu.price * quantity.- The result stays on the object. After three calls to
add,order.totalis 89, the total for that table. cancelchecks first withif. Cancelling 30 teas makescutequal to5 * 30, which is $150. That is bigger than $89. So onlyprint("Can't cancel that")runs, andself.totalis not changed at all.- An object can be sent as an argument:
menu.pricereads an attribute of theMenuobject that was sent.
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']
- Python looks for
self.itemon the object first. Objectahas noitem, so Python uses the one on the class. As a result, table 1 and table 2 write into the same list. - The fix: make the list in
__init__withself.item = []. Each object gets its own list:a.itembecomes['coffee with milk']andb.itembecomes['sweet tea']. - Class attributes are good for values that really are the same for every object, such as
STALL_NAME = "Mr. Darto's Coffee Stall".
__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)]
__str__is for users:print(obj),str(obj)and f-strings call it (objstands for any object). It holds text that is easy to read.__repr__is for developers:repr(obj)calls it, the REPL (Python's interactive mode) and debuggers (tools for finding bugs) show it, and it is used when the object is inside a list. Ideally it looks like code that would make the object again.- If you only want to write one, write
__repr__. Python also uses it forprintwhen there is no__str__. The opposite is not true: without__repr__, a list still prints<__main__.Menu object at ...>. - Both must
returntext, notprintit. __len__makeslen(obj)work. IfOrderhasdef __len__(self): return len(self.item), thenlen(order)callsorder.__len__()and gives the number of items. Without that method, you getTypeError: object of type 'Order' has no len(). Python does not use other names such as__size__or__length__.
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
name: strnames one attribute,name, with its type hint (a note about the type, covered in the lesson Type Hints). Python does not check that type.- Use
@dataclassfor a class that mainly holds data. Write__init__yourself when the constructor needs to do something else, for example refuse a negative price. This lesson writes__init__by hand so you can see how it works.
⚠️ A forgotten self and a misspelt __init__
- Forgetting
selfin a method's parameters.def total(quantity):thencoffee.total(3)fails:TypeError: Menu.total() takes 1 positional argument but 2 were given. It says "2 were given" because Python also sendscoffeeasself. - Forgetting
self.when storing.name = namein__init__only fills a local variable, which disappears when__init__ends. Thencoffee.nameraisesAttributeError: 'Menu' object has no attribute 'name'. - Misspelling
__init__. Python treats__int__as an ordinary method, soMenu("coffee with milk", 15)is refused:TypeError: Menu() takes no arguments. - A list in the class body.
item = []outside__init__is shared by every object. Make it in__init__withself.item = [].
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.