A class is a template for making objects. Each object made from the class (an instance) has its own data, called attributes, and shares the functions defined in the class, called methods.
The program
python
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed self.tricks = [] def bark(self): return f"{self.name} says: Woof!" def learn(self, trick): self.tricks.append(trick) rex = Dog("Rex", "Labrador") bella = Dog("Bella", "Beagle") rex.learn("sit") rex.learn("roll over") print(rex.bark()) print(f"{rex.name} the {rex.breed} knows: {rex.tricks}") print(f"{bella.name} the {bella.breed} knows: {bella.tricks}")
output
Rex says: Woof! Rex the Labrador knows: ['sit', 'roll over'] Bella the Beagle knows: []
How it works
Dog("Rex", "Labrador")creates a new object and then calls__init__with it.__init__sets up the starting attributes.selfis the object the method is working on. When you writerex.learn("sit"), Python callsDog.learn(rex, "sit"), so inside the methodselfisrex.self.tricks = []is inside__init__, so every dog gets its own new list. That is why teaching Rex a trick does not change Bella.
A readable print
Printing the object itself gives a default text such as <__main__.Dog object at 0x7f...>. Add a __repr__ method to choose what is shown:
python
class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def __repr__(self): return f"Dog({self.name!r}, {self.breed!r})" print(Dog("Rex", "Labrador"))
output
Dog('Rex', 'Labrador')