Classes and objects
A class is a blueprint that bundles data (attributes) and behaviour (methods); each object made from it is an instance. You define one with class Name:, set up its data in __init__(self, ...), and reach that data through self. Classes are worth it when several functions keep working on the same piece of data.
Your first class
class BankAccount:
def __init__(self, owner: str, balance: float = 0) -> None:
self.owner = owner
self.balance = balance
def deposit(self, amount: float) -> None:
self.balance += amount
def withdraw(self, amount: float) -> None:
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
account = BankAccount("Asha", 100)
account.deposit(50)
account.withdraw(30)
print(account.owner, account.balance)Asha 120
__init__runs automatically when you create an object:BankAccount("Asha", 100).selfis the object itself.self.balanceis that account's own balance.- Methods are functions inside the class; Python passes
selffor you. - Class names use
CapWords; methods and attributes usesnake_case.
A readable print-out with __repr__
class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __repr__(self) -> str:
return f"Point(x={self.x}, y={self.y})"
def distance_to_origin(self) -> float:
return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3, 4)
print(p)
print(p.distance_to_origin())Point(x=3, y=4) 5.0
Without __repr__, printing an object shows something like <__main__.Point object at 0x7f...>. Methods with double underscores are "dunder" methods: hooks Python calls for you.
Class attributes
class Employee:
company = "PythonMates" # shared by all instances
headcount = 0
def __init__(self, name: str) -> None:
self.name = name # one per instance
Employee.headcount += 1
a = Employee("Ana")
b = Employee("Ben")
print(a.company, b.company)
print(Employee.headcount)PythonMates PythonMates 2
Inheritance
class Shape:
def __init__(self, name: str) -> None:
self.name = name
def area(self) -> float:
raise NotImplementedError
def describe(self) -> str:
return f"{self.name} with area {self.area():.1f}"
class Rectangle(Shape):
def __init__(self, width: float, height: float) -> None:
super().__init__("rectangle")
self.width = width
self.height = height
def area(self) -> float:
return self.width * self.height
class Circle(Shape):
def __init__(self, radius: float) -> None:
super().__init__("circle")
self.radius = radius
def area(self) -> float:
return 3.14159 * self.radius ** 2
for shape in [Rectangle(3, 4), Circle(1)]:
print(shape.describe())rectangle with area 12.0 circle with area 3.1
A subclass reuses everything from its parent and overrides what's different. super().__init__(...) runs the parent's setup. Keep hierarchies shallow — one or two levels is plenty.
Properties: computed and protected attributes
class Temperature:
def __init__(self, celsius: float) -> None:
self.celsius = celsius
@property
def fahrenheit(self) -> float:
return self.celsius * 9 / 5 + 32
@property
def celsius(self) -> float:
return self._celsius
@celsius.setter
def celsius(self, value: float) -> None:
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
t = Temperature(20)
print(t.fahrenheit)
t.celsius = 30
print(t.fahrenheit)
try:
t.celsius = -300
except ValueError as err:
print("Error:", err)68.0 86.0 Error: below absolute zero
Practice
Write a class Counter with a count attribute starting at 0, a method increment(step=1) that adds to it, and a __repr__ that returns Counter(count=N). Create one, increment it once by default and once by 5, then print it.
Counter(count=6)