A class bundles data and behaviour. An object is an instance of a class.
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def describe(self):
return f"{self.name}: {self.score}"
student = Student("Ada", 95)
print(student.describe())Ada: 95
init#
__init__ runs when you create an object. It initialises the instance attributes.
class Counter:
def __init__(self, start=0):
self.value = start
def increment(self):
self.value += 1
def reset(self):
self.value = 0
counter = Counter()
counter.increment()
counter.increment()
print(counter.value) # 2self refers to the object being operated on. It is the first parameter of instance methods and is passed automatically when you call the method.
Attributes and methods#
Attributes hold state; methods define behaviour:
class Rectangle:
def __init__(self, width, height):
if width < 0 or height < 0:
raise ValueError("Dimensions must be non-negative")
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
box = Rectangle(3, 4)
print(box.area()) # 12
print(box.perimeter()) # 14Validation in __init__ prevents objects from starting in an invalid state.
Class attributes#
An attribute defined on the class is shared unless an instance overrides it:
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.pi * self.radius ** 2
print(Circle.pi)
print(Circle(2).area())Mutable class attributes are shared across instances and are a common source of bugs. Put per-object data in __init__.
Readable representation#
__repr__ controls the developer-facing representation. It is useful in the console and in debugging output:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
print(Point(2, 5))Point(x=2, y=5)
print() uses __str__ when defined and falls back to __repr__ otherwise. For small data classes, a clear __repr__ is worth the two lines.
Objects in collections#
class Task:
def __init__(self, title, done=False):
self.title = title
self.done = done
tasks = [
Task("Write outline"),
Task("Draft tutorial", done=True),
]
for task in tasks:
status = "done" if task.done else "pending"
print(f"[{status}] {task.title}")A list of objects is often clearer than a list of loosely related dictionaries once the data has behaviour or validation rules.
Composition versus inheritance#
Start with composition: an object uses other objects.
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
return self.engine.start()
print(Car().start())Inheritance is appropriate when a subtype genuinely shares the parent's interface and behaviour. Do not introduce a hierarchy just to reuse one helper function; a plain function or composition is usually simpler.
Practice#
Create a BankAccount class with an owner, balance, deposit(amount), and withdraw(amount). Reject negative amounts with ValueError and withdrawals above the balance with a custom exception. Create two accounts, perform several operations, and print each account using __repr__.
