Classes and Objects
Classes and Objects
Defining a class
Use class and __init__ for the constructor:
pythonclass Car: def __init__(self, brand, year): self.brand = brand self.year = year def describe(self): return f\"{self.brand} ({self.year})\"
self is the instance. You pass it explicitly; Python does not hide it.
Creating instances
pythonmy_car = Car(\"Toyota\", 2020) print(my_car.describe()) # Toyota (2020)
Inheritance
pythonclass ElectricCar(Car): def __init__(self, brand, year, range_km): super().__init__(brand, year) self.range_km = range_km
Subclasses override methods by defining a method with the same name.