Data and the functions that change it
Say we are writing a small battle game. Each unit in it has a name, some hit points, and a maximum it can't be healed past. Two things happen to a unit: it gets hit, and it gets healed. Whatever happens, its hit points have to stay between 0 and that maximum.
You can already write this with what you know. A unit is a record, a data class with three fields, and each thing that happens to a unit is a function that takes the record:
@dataclass
class Unit:
name: str
hp: int
max_hp: int
def take_hit(unit, damage):
unit.hp = max(unit.hp - damage, 0)
def heal(unit, amount):
unit.hp = min(unit.hp + amount, unit.max_hp)
aria = Unit('Aria', 10, 10)
take_hit(aria, 4)
heal(aria, 9)
print(aria.hp)
aria.hp -= 15
print(aria.hp)The program prints 10 and then −5. Aria takes 4 damage and drops to 6, the heal of 9 stops at her maximum of 10, and so far the rule holds. Then the line aria.hp -= 15 changes the record directly. It skips both functions and leaves her at −5 hit points.
The rule about 0 and the maximum is written inside take_hit and heal, but nothing ties those two functions to the record, which is why that last line could go around them. In a real game they would sit among dozens of other functions, and everyone working on the code would have to know they exist and remember to use them instead of changing hp by hand. Every call also has to pass the unit in.
Strings and lists don't work this way. When you write nums.append(4), the operation comes with the list: you don't go looking for a separate function that adds to lists. A class lets you make your own kind of value that works like that. It says, in one place, what data each value holds and which methods act on it.
You have seen two small pieces of this already. The ticketer kept a number that only take could change, and the @dataclass line turned a class statement into a record by writing its constructor for you. Now we write a class ourselves, with its methods.
Defining a class
Here is the unit as a class. The def statements inside the class body are its methods. The one named __init__, with two underscores on each side, is special: Python runs it whenever a new unit is made, and it gives the unit its starting attributes, the named values stored on it, like a data class's fields. A new unit starts at full health, so __init__ takes only the name and the maximum and sets hp from max_hp. The constructor that @dataclass writes could not do that, because it sets each field straight from an argument.
Every method's first parameter is the unit the method is working on, and by convention it is called self. Inside __init__, self.name = name stores name on that unit.
class Unit:
def __init__(self, name, max_hp):
self.name = name
self.max_hp = max_hp
self.hp = max_hp
def take_hit(self, damage):
self.hp = max(self.hp - damage, 0)
def heal(self, amount):
self.hp = min(self.hp + amount, self.max_hp)
aria = Unit('Aria', 10)
bram = Unit('Bram', 8)
aria.take_hit(4)
bram.take_hit(12)
aria.heal(9)
print(aria.name, aria.hp)
print(bram.name, bram.hp)The program prints Aria 10 and Bram 0. Each call to Unit(...) makes a new object, called an instance of the class. aria and bram are two instances, each with its own hp, so hitting Bram for 12 drops him to 0 and leaves Aria alone.
Now compare a call with its definition. take_hit is defined with two parameters, self and damage, but called with one. That is because Python passes the object before the dot as the first argument: aria.take_hit(4) runs Unit.take_hit(aria, 4). So inside the method, self is aria, and self.hp is Aria's hit points.
You may have noticed that the class doesn't stop aria.hp -= 15. Python has no private keyword to forbid it. The convention is to start the name of an attribute that outside code should leave alone with an underscore, such as _hp, which marks an abstraction barrier. In practice, once a class has methods, you change a unit by calling them.
Step through making a unit and hitting it
Step through the first preset and watch where things end up. The class and the new unit both appear in the column headed Objects, beside the frames. As __init__ runs, name, max_hp and hp appear on the object, not in the frame of __init__, so they are still there after the call returns.
The second preset hits Aria for 15, more than she has, and her hit points stop at 0. The third makes two units and hits only Bram, and Aria still has all 10.
Inheritance: kinds of units
Now the game gets two kinds of unit. A knight wears armor that takes 3 off every hit. A healer has a healing power and can mend another unit by that much.
With one class, you could add a kind attribute and check it. take_hit would start with if self.kind == 'knight':, and mend would have to refuse to work unless the unit is a healer. Every new kind would add another branch to Unit, and the code for one kind would end up spread across all of its methods.
Inheritance lets you write each kind as its own class that starts from Unit. class Knight(Unit): makes Knight a subclass of Unit, and Unit its base class. A Knight has everything a Unit has, and its class body lists only what is different. Knight writes its own take_hit; a method in a subclass that replaces one from the base class is an override. Healer adds an attribute and a method.
class Unit:
def __init__(self, name, max_hp):
self.name = name
self.max_hp = max_hp
self.hp = max_hp
def take_hit(self, damage):
self.hp = max(self.hp - damage, 0)
def heal(self, amount):
self.hp = min(self.hp + amount, self.max_hp)
class Knight(Unit):
def take_hit(self, damage):
super().take_hit(max(damage - 3, 0))
class Healer(Unit):
def __init__(self, name, max_hp, power):
super().__init__(name, max_hp)
self.power = power
def mend(self, other):
other.heal(self.power)
aria = Knight('Aria', 10)
bram = Healer('Bram', 8, 3)
aria.take_hit(5)
bram.take_hit(5)
print(aria.hp, bram.hp)
bram.mend(aria)
print(aria.hp)You get 8 3 and then 10. Aria the knight is hit for 5, her armor takes 3 off, and she loses 2. Bram the healer has no armor and loses all 5. Then Bram mends Aria for 3, which would take her to 11, but heal stops at her maximum of 10.
Knight's take_hit takes the armor off the damage and hands the rest to Unit's version with super().take_hit(...), instead of repeating Unit's work. super() reaches the base class's methods and calls them on the same object. Healer uses it the same way in __init__. It needs one more attribute, power, so it writes its own __init__, lets super().__init__(name, max_hp) set the other three, and then sets power.
Notice also that mend calls other.heal(...) instead of changing other.hp itself, so the rule about the maximum still lives in one place.
Definition
Finding a method
To evaluate obj.name, Python looks for name on the object itself, then in the object's class, then in that class's base class, and uses the first one it finds. So aria.take_hit finds Knight's version, and aria.heal goes on to Unit's.
Step through a knight taking a hit
In the first preset, watch the two take_hit frames. Knight's opens first, because the lookup reaches Knight before Unit, and its super() call then opens Unit's on the same object.
In the second preset the knight is hit for 2, and the armor takes all of it: Unit's version gets 0 and hp stays 10. The third preset makes a plain Unit, so the call goes straight to Unit's take_hit and nothing is taken off.
Use inheritance only when the new class is a kind of the base class: every knight is a unit, and a knight can go anywhere a unit is expected. When one thing has another, give it an attribute instead. A squad has units, so a Squad class would store a list of units. It should not inherit from Unit, because a squad has no hit points of its own.
One function for every kind of unit
So far each call named a unit whose kind we knew. Most of a game handles units together. Say an explosion hits every unit in a squad for 4. The function hit_all takes a list of units and calls take_hit on each, without asking what kind each one is.
class Unit:
def __init__(self, name, max_hp):
self.name = name
self.max_hp = max_hp
self.hp = max_hp
def take_hit(self, damage):
self.hp = max(self.hp - damage, 0)
def heal(self, amount):
self.hp = min(self.hp + amount, self.max_hp)
class Knight(Unit):
def take_hit(self, damage):
super().take_hit(max(damage - 3, 0))
class Healer(Unit):
def __init__(self, name, max_hp, power):
super().__init__(name, max_hp)
self.power = power
def mend(self, other):
other.heal(self.power)
def hit_all(units, damage):
for u in units:
u.take_hit(damage)
squad = [Knight('Aria', 10), Healer('Bram', 8, 3), Unit('Cole', 6)]
hit_all(squad, 4)
squad[1].mend(squad[2])
for u in squad:
print(u.name, u.hp)The squad ends with Aria at 9, Bram at 4 and Cole at 5. Aria's armor turned the 4 into 1, Bram and Cole lost all 4, and Bram then mended Cole from 2 back up to 5.
hit_all doesn't check a unit's kind. u.take_hit(4) looks up take_hit starting from each object, so the version that runs comes from each object's own class: the Knight in the list finds Knight's version, and the others find Unit's.
What hit_all relies on is that every element has a take_hit method that takes a number. The attributes and methods other code relies on make up a class's interface. In Python, any object with that method would work, even one from a class that has nothing to do with Unit, such as a wall that loses a point of strength per hit.
Deeper read: multiple inheritance
A class can list more than one base class. A paladin that wears a knight's armor and mends like a healer is class Paladin(Knight, Healer): pass. To find a method on a paladin, Python searches Paladin, Knight, Healer, Unit and finally object, the base of every class, in that order; Paladin.mro(), short for method resolution order, returns that list. So take_hit comes from Knight, __init__ and mend from Healer, and heal from Unit.
Many programs avoid these rules by inheriting from one class and holding anything else as attributes.
Printing an object
Try printing a unit and Python shows something like <__main__.Unit object at 0x105aee850>: the class name and where the object is in memory. That's no use in a game log. Python gets the text for print and f-strings by calling the object's __str__ method, and a class can define its own:
class Unit:
def __init__(self, name, max_hp):
self.name = name
self.max_hp = max_hp
self.hp = max_hp
def take_hit(self, damage):
self.hp = max(self.hp - damage, 0)
def __str__(self):
return f'{self.name} {self.hp}/{self.max_hp}'
aria = Unit('Aria', 10)
aria.take_hit(4)
print(aria)
print(f'After one hit: {aria}')Both lines show Aria 6/10. Since Knight and Healer inherit from Unit, they get the same __str__.
Inside a list, Python shows each element with repr(), which calls the method __repr__ instead of __str__, so print([aria]) still shows the address. __repr__ is meant to be unambiguous text for a programmer, ideally the expression that would build the object: Time(18, 6) says what kind of value it is, while 06:06 PM could be a string. A class that defines only __repr__ gets it for print as well.
Clock Conversion is practice for this part. It gives times on a 24-hour clock and asks for each one on a 12-hour clock, so a Time class whose __str__ gives the 12-hour form handles the conversion, and the main loop only reads and prints.
Each test case gives a time in 24-hour format, hh:mm, with hours 00 to 23 and minutes 00 to 59. Print the same time in 12-hour format, hh:mm AM or hh:mm PM, keeping leading zeros. In 12-hour format each half of the day numbers its hours 12, 01, 02, up to 11.
Constraints
- test cases
- Each time is a valid 24-hour time
Sample · Input
11 09:41 18:06 12:14 00:59 00:00 14:34 01:01 19:07 11:59 12:00 21:37
Output
09:41 AM 06:06 PM 12:14 PM 12:59 AM 12:00 AM 02:34 PM 01:01 AM 07:07 PM 11:59 AM 12:00 PM 09:37 PM
class Time:
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
def __str__(self):
if self.hour < 12:
half = 'AM'
else:
half = 'PM'
h = self.hour % 12
if h == 0:
h = 12
return f'{h:02d}:{self.minute:02d} {half}'
t = int(input())
for _ in range(t):
hh, mm = input().split(':')
print(Time(int(hh), int(mm)))The 12-hour form needs care in two places. 18 % 12 is 6, but hours 0 and 12 both give 0, and a 12-hour clock calls both of them 12: midnight is 12:00 AM and noon is 12:00 PM. And the format :02d pads a number to two digits, so 6 prints as 06. The problem's sample input includes 00:00, 12:00 and 00:59, so it checks both.
Operators on your own types
Some values need + and <. You can add minutes to a clock time, and two times can be compared and sorted from morning to night. A class can give its objects their own operators. (Units don't get any, because adding two units means nothing.)
You have now met three methods your code never calls by name: Python calls __init__ when an object is made, __str__ when it is printed and __repr__ when it is shown inside a list. Methods like these are special methods, and each operator has one. Python turns a + b into a.__add__(b), so a class that defines __add__ can be added.
| Syntax | Python calls | C++ defines |
|---|---|---|
a + b | a.__add__(b) | operator+ |
a == b, a < b | a.__eq__(b), a.__lt__(b) | operator==, operator< |
len(a), a[i] | a.__len__(), a.__getitem__(i) | a size() member, operator[] |
print(a), repr(a) | a.__str__(), a.__repr__() | operator<< on an ostream |
Example: adding and comparing times
Adding minutes to a time should give a time, and the sum should wrap past midnight: 23:50 plus 25 minutes is 00:15. Comparing two times should compare them as moments of the day.
Both are easier through one helper method, minutes, which turns a time into minutes since midnight. __add__ adds, takes the remainder modulo , the number of minutes in a day, and turns the result back into hours and minutes. __eq__ and __lt__ compare minutes.
class Time:
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
def __repr__(self):
return f'Time({self.hour}, {self.minute})'
def minutes(self):
return self.hour * 60 + self.minute
def __add__(self, extra):
total = (self.minutes() + extra) % (24 * 60)
return Time(total // 60, total % 60)
def __eq__(self, other):
return self.minutes() == other.minutes()
def __lt__(self, other):
return self.minutes() < other.minutes()
late = Time(23, 50)
print(late + 25)
print(late + 10 == Time(0, 0))
print(Time(9, 0) < Time(8, 59))
print(sorted([Time(9, 41), Time(0, 59), late, Time(12, 0)]))For late + 25, late.minutes() is , and
so the sum is Time(0, 15). late + 10 is , midnight, so it equals Time(0, 0). Addition builds a new Time and leaves late unchanged, the way + on numbers leaves both numbers alone.
Sorting works through the comparisons. Python's sort compares elements with <, so sorted can order times once __lt__ exists, and the sorted list prints as [Time(0, 59), ...] because a list shows its elements with __repr__.
Once a class defines __eq__, Python no longer lets its objects go in a set or be dictionary keys: {late} raises a TypeError saying the type is unhashable. A set finds a value through its hash, so two values that are equal must have the same hash, and Python can't tell whether that holds for your __eq__. A __hash__ method that returns hash(self.minutes()) makes it work again, as long as you don't change a time while it is in a set.
Rank List is practice for comparisons. A team ranks higher with more solved problems, or the same number and less penalty time. A Team class whose __lt__ encodes that rule and whose __eq__ says when two teams share a place lets teams.sort() produce the results table. (The other way is a key function, which orders the teams without changing the class.)
Common mistakes
Leaving out
selfin a Python method definition.- Where it breaks
- With
def take_hit(damage):, the callaria.take_hit(4)passes two arguments,ariaand 4, to a function that takes one, and Python stops withTypeError: Unit.take_hit() takes 1 positional argument but 2 were given. - The fix
- Give every method
selfas its first parameter:def take_hit(self, damage):.
Writing
hp = max_hpinstead ofself.hp = max_hpin__init__.- Where it breaks
- The assignment makes a name in the frame of
__init__, which disappears when the call returns, soaria.hpstops the program withAttributeError: 'Unit' object has no attribute 'hp'. - The fix
- Store each attribute through
self:self.hp = max_hp.
Listing attributes in a plain Python class body the way a data class lists its fields.
- Where it breaks
- In a class without
@dataclass,inventory = []in the body makes one list that belongs to the class and is shared by every unit. Afteraria.pick_up('sword')appends to it,bram.inventoryis['sword']too. - The fix
- Create each unit's own list in
__init__:self.inventory = [].
Calling the method itself, instead of the base class's version, inside an override.
- Where it breaks
- With
self.take_hit(max(damage - 3, 0))in Knight'stake_hit(or plaintake_hit(...)in C++), the call finds Knight's version again, which calls itself again without end. Python stops withRecursionError: maximum recursion depth exceeded, and the C++ program runs until it crashes or hits the time limit. - The fix
- Call the base version:
super().take_hit(...)in Python,Unit::take_hit(...)in C++.
Leaving out
virtualon a C++ member function that a derived class replaces.- Where it breaks
- In
hit_all,u->take_hit(4)then runs Unit's version for every unit, so Aria the knight drops from 10 to 6 instead of 9. The compiler reports no error unless Knight's version is markedoverride. - The fix
- Mark the base version
virtualand each replacementoverride, so the compiler checks that they match.
Recall A knight with 10 hit points is hit for 2. Which `take_hit` versions run, and how many hit points does it have afterwards?
Both run. Knight's runs first, because the lookup reaches Knight before Unit. It takes the armor off, max(2 − 3, 0) = 0, and passes 0 to Unit's version through super(), so hp stays 10.
Recall Why can `hit_all` call `take_hit` on every unit without checking what kind each one is?
Because the lookup for u.take_hit starts at each object's own class. A Knight finds Knight's version; a Healer or a plain Unit finds Unit's.
Key terms
| Term | Meaning |
|---|---|
| class | A definition of a kind of object: the data each one holds and the methods that act on it. |
| instance | One object made from a class. |
__init__ / constructor | The method that runs when an object is made and gives it its starting data. |
self / this | The object a method was called on: a parameter in Python, a pointer in C++. |
public / private | C++: whether any code, or only the class's own member functions, may use a member. |
| inheritance | Defining a class that starts with everything another class has. |
| base class | The class another class inherits from. |
| subclass / derived class | A class that inherits from a base class and lists only what differs. |
| override | A subclass's replacement for a method of its base class. |
super() | Python: reaches the base class's version of a method, called on the same object. |
virtual | C++: a member function whose calls run the version for the object's actual type. |
| slicing | C++: copying a derived object into a base-class variable, which keeps only its base part. |
| interface | The attributes and methods other code relies on an object to have. |
__str__ / __repr__ | The readable text for an object, and the unambiguous text a list shows. |
| special method | A method such as __add__ that Python calls for a piece of syntax. |
| operator overloading | C++: defining what an operator such as + or << does for a type. |