Skip to content

Classes

A Python class is a blueprint for creating objects that bundle data (attributes) and behavior (methods). It defines a custom type by specifying the structure and functionality that its instances will have, supporting encapsulation and reuse. Classes enable object-oriented features like inheritance and polymorphism, allowing extension and customization of behavior.

Defining a class

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display(self):
        print(f" {self.year} {self.make} {self.model}")
  • init() : is the instance initializer that runs automatically after a new object is created typically used to set up initial state (attributes) for that instance.
  • self : is the reference to the current object, passed as the first parameter to instance methods so you can access and modify the object attributes and call its other methods.

Declaring an instance of a class

car = Car("Volvo", "XC90", "2023")
car.display()
car.model = "XC60"
car.display()
 2023 Volvo XC90
 2023 Volvo XC60

Inheritence

class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)

car = ElectricCar("Rivian", "R1S", "2023")
car.display()
 2023 Rivian R1S

  • super(): is a built-in function in Python that provides access to methods in a parent or superclass from a child class. It's commonly used in inheritance to call methods from the parent class, especially in the init method.