Show contents
Chapter 1 of 6 · 20 min
Classes: grouping data and actions
By the end of this chapter, you'll be able to
- Define a class with __init__, attributes and methods
- Create several independent objects from the same class
- Make an object readable when displayed with __str__
- Protect an attribute with the _ convention and a property
A class, some objects
A class is a blueprint: it describes the attributes (the data) and methods (the actions) its objects will have. An object, or instance, is a copy built from that blueprint.
class PiggyBank:
def __init__(self, owner, goal):
self.owner = owner
self.goal = goal
self.balance = 0
def deposit(self, amount):
if amount <= 0:
raise ValueError("the deposit must be positive")
self.balance += amount
def progress(self):
return round(100 * self.balance / self.goal)
def __str__(self):
return f"{self.owner}'s piggy bank: {self.balance}/{self.goal} ({self.progress()} %)"
bike = PiggyBank("Nadia", 150)
bike.deposit(40)
bike.deposit(35)
print(bike)
books = PiggyBank("Tomás", 60)
books.deposit(15)
print(books)
print(bike.balance, books.balance)
Nadia's piggy bank: 75/150 (50 %)
Tomás's piggy bank: 15/60 (25 %)
75 15
Let's break it down:
class PiggyBank:defines the class. By convention, its name starts with a capital letter.__init__is the constructor: Python calls it automatically when you writePiggyBank("Nadia", 150), to initialise the new object.selfrefers to the current object.self.balance = 0creates an attribute that belongs to this object: Nadia's piggy bank and Tomás's each have their own balance.- A method is a function defined in the class. Its first parameter is always
self. You call it with a dot:bike.deposit(40), and Python passesbikeasself. __str__returns the text displayed byprint(object).
print calls __str__, which itself uses the progress() method.
Text description of the animation
- We create a piggy bank, then only handle it through its methods.
- Python creates an empty object and calls __init__: self is this new object, which receives its three attributes.
- bike.deposit(40) calls the method with self = bike. The amount is positive: the balance goes up to 40.
- Second deposit: 75.
- print calls __str__, which itself uses the progress() method.
Without __str__, print would display something like <__main__.PiggyBank object at 0x7f3a…>: the class name and an address in memory, not very helpful.
Protecting an attribute
Here, nothing yet stops anyone from writing bike.balance = -500 and getting round the rule in deposit. Python has no truly private attributes, but it has two tools:
- the
_convention: an attribute named_balancesignals "internal to the class, don't touch it from outside"; - the property:
@propertyturns a method into a read-only attribute.
class PiggyBank:
def __init__(self, owner, goal):
self.owner = owner
self.goal = goal
self._balance = 0
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("the deposit must be positive")
self._balance += amount
p = PiggyBank("Nadia", 150)
p.deposit(40)
print(p.balance)
try:
p.balance = 1_000_000
except AttributeError as error:
print("Refused:", error)
40
Refused: property 'balance' of 'PiggyBank' object has no setter
You read p.balance like an attribute, but you can't assign it: the only way to change the balance is deposit, which applies the rule. This principle is called encapsulation. (1_000_000 is written with _ to make it easier to read: it's the number one million.)
Your turn
Worked exercise
Worked exercise: the car park
Write a class CarPark with a capacity. Methods: enter(plate) raises a ValueError if the car park is full or if the car is already inside; leave(plate) raises a ValueError if the car isn't there; free_spaces() returns the number of spaces left; __str__ displays Car park: 1/2 occupied. Test it with a 2-space car park.
Hint 1
set()): plate in self.cars is fast, and a set never contains a duplicate.Hint 2
(p.enter, "AB-123") lets you test a whole series of actions in a single loop.Show the solution and common mistakes
class CarPark:
def __init__(self, capacity):
self.capacity = capacity
self.cars = set()
def enter(self, plate):
if plate in self.cars:
raise ValueError(f"{plate} is already in the car park")
if len(self.cars) >= self.capacity:
raise ValueError("car park full")
self.cars.add(plate)
def leave(self, plate):
if plate not in self.cars:
raise ValueError(f"{plate} isn't in the car park")
self.cars.remove(plate)
def free_spaces(self):
return self.capacity - len(self.cars)
def __str__(self):
return f"Car park: {len(self.cars)}/{self.capacity} occupied"
p = CarPark(2)
actions = [(p.enter, "AB-123"), (p.enter, "CD-456"), (p.enter, "EF-789"), (p.leave, "AB-123"), (p.leave, "ZZ-000")]
for method, plate in actions:
try:
method(plate)
except ValueError as error:
print("Refused:", error)
print(p, "-", p.free_spaces(), "free space(s)")
Refused: car park full
Refused: ZZ-000 isn't in the car park
Car park: 1/2 occupied - 1 free space(s)
Common mistakes:
- Creating
cars = set()at class level rather than in__init__: every car park would share the same set of cars. - Testing
len(self.cars) > self.capacity: the extra car would be accepted before the test refused it. The correct comparison is>=.
Summary
- 1A class describes attributes and methods; each object has its own values.
- 2__init__ initialises the object, self refers to the current object.
- 3__str__ defines the text displayed by print.
- 4An _internal attribute and a @property protect the class's rules.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.