Classes & Objects
Class vs object
- A class is a blueprint: it defines what data (attributes) and behaviour (methods) things have.
- An object (instance) is one thing built from it:
rex = Dog("Rex", "Labrador").
The pieces
__init__runs when an object is created and sets up its attributes.selfis the object itself. Python passes it automatically as the first argument of every method.- Instance attributes (
self.name) belong to one object. - Class attributes (
species = "dog") are shared by all objects.
Methods
- Normal methods take
self. @classmethodtakescls, often used as an alternative constructor (Dog.from_string("Rex,Lab")).@staticmethodtakes neither: a helper that lives in the class.
💡 Add a __repr__ method so printing an object shows something useful (see Dunder Methods).
▶️ Runs in the app.
Example
class Dog:
species = "Canis familiaris" # class attribute (shared)
def __init__(self, name, breed):
self.name = name # instance attributes
self.breed = breed
self.tricks = []
def bark(self):
return f"{self.name} says Woof!"
def learn(self, trick):
self.tricks.append(trick)
@classmethod
def from_string(cls, text):
name, breed = text.split(",")
return cls(name.strip(), breed.strip())
rex = Dog("Rex", "Labrador")
rex.learn("sit")
print(rex.bark()) # Rex says Woof!
print(rex.tricks, rex.species) # ['sit'] Canis familiaris
bella = Dog.from_string("Bella, Beagle")
print(bella.name, bella.breed) # Bella Beagle