Classes and Objects
A class is a blueprint for creating objects that bundle data (attributes) together with the functions that operate on that data (methods). Every dog you create from a Dog class shares the same structure, but holds its own values.
main.py
Try it yourself →class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Rex", 3)
print(my_dog.name)
print(my_dog.bark())Output
Rex Rex says Woof!
- __init__ runs automatically when you create a new object — it's where you set up the object's starting data
- self refers to the specific object the method is being called on — it's always the first parameter of a method
- self.name = name stores the value as an attribute, so every method on this object can access it later
- Dog("Rex", 3) creates an actual object (an "instance") of the Dog class
You could create as many dogs as you want from the same class — Dog("Bella", 5), Dog("Max", 1) — each one keeping its own name and age independently.
Next: modules — using Python's standard library instead of writing everything from scratch.
Practice exercise
Add a honk() method to the Car class that returns f"{self.make} says beep!", then print the result of calling it on a Car("Toyota").