class statement
class defines a new type of object that bundles data (attributes) and the functions that work on it (methods) under one name.
class Name(BaseClass):
def __init__(self, arg):
self.arg = arg
def method(self):
...A class is a blueprint. From one class BankAccount: you can create as many account objects (called instances) as you like, each with its own data: its own owner and its own balance.
__init__ runs when you create an object and sets up its attributes on self, which means "this particular object". Other functions inside the class are methods; they also take self first, so they can read and change that object's data.
Printing an object normally shows an unhelpful text with a memory address. Define __repr__ to choose what it looks like. A class can also inherit from another, reusing its methods and adding or changing some.
Examples
1A first class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof"
rex = Dog("Rex", 3)
luna = Dog("Luna", 5)
print(rex.bark())
print(luna.name, luna.age)Rex says woof Luna 5
2Methods that change the object
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough money")
return
self.balance -= amount
acc = BankAccount("Nadia", 100)
acc.deposit(50)
acc.withdraw(500)
acc.withdraw(30)
print(acc.owner, acc.balance)Not enough money Nadia 120
3A readable print with __repr__
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"Product({self.name!r}, {self.price})"
basket = [Product("tea", 3.5), Product("honey", 7.0)]
print(basket[0])
print(basket)Product('tea', 3.5)
[Product('tea', 3.5), Product('honey', 7.0)]4Inheritance
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def yearly(self):
return self.salary * 12
class Manager(Employee):
def __init__(self, name, salary, bonus):
super().__init__(name, salary)
self.bonus = bonus
def yearly(self):
return super().yearly() + self.bonus
for person in [Employee("Lars", 3000), Manager("Aiko", 4000, 5000)]:
print(person.name, person.yearly())Lars 36000 Aiko 53000
super() calls the parent class's version of a method.
5Class attributes and a dataclass
For classes that mostly hold data, @dataclass writes __init__, __repr__ and == for you.
from dataclasses import dataclass
@dataclass
class City:
name: str
population: int
country: str = "unknown"
a = City("Porto", 230000, "Portugal")
print(a)
print(a == City("Porto", 230000, "Portugal"))City(name='Porto', population=230000, country='Portugal') True
Common mistakes
Forgetting self
Every method needs self as its first parameter, and attributes must be written as self.name. Without self., the value is a local variable that disappears when the method ends.
class Counter:
def __init__(self):
count = 0
c = Counter()
print(hasattr(c, "count"))False
Sharing a list between all objects
A list written directly in the class body is shared by every instance. Create it in __init__ instead.
class Team:
members = []
def add(self, name):
self.members.append(name)
a, b = Team(), Team()
a.add("Eva")
print(b.members)
class BetterTeam:
def __init__(self):
self.members = []
a, b = BetterTeam(), BetterTeam()
a.members.append("Eva")
print(b.members)['Eva'] []
Questions people ask
What is self in Python?
The object the method was called on. acc.deposit(50) is really BankAccount.deposit(acc, 50), so self is acc.
What is __init__?
The method Python calls right after creating a new object, to fill in its starting attributes. It is often called the constructor.
What is the difference between __repr__ and __str__?
__repr__ is for developers and should look like code; __str__ is for users and is used by print() if it exists. Without __str__, print() uses __repr__.