def charge(self): print("Charging...") In the above example, the ElectricCar class inherits from the Car class and adds an additional attribute battery_capacity and a method charge . Polymorphism is the ability of an object to take on multiple forms. This can be achieved through method overriding or method overloading. Method Overriding class Rectangle: def __init__(self, width, height): self.width = width self.height = height
An , on the other hand, is an instance of a class. It has its own set of attributes (data) and methods (functions). Defining a Class class Car: def __init__(self, color, model, year): self.color = color self.model = model self.year = year python 3 deep dive part 4 oop
def honk(self): print("Honk!") In the above example, we define a Car class with an initializer method ( __init__ ) that takes in color , model , and year parameters. We also define a honk method that prints "Honk!". my_car = Car("Red", "Toyota", 2015) print(my_car.color) # Output: Red my_car.honk() # Output: Honk! Here, we create an object my_car from the Car class and access its attributes and methods. Inheritance Inheritance is a mechanism in OOP that allows one class to inherit the properties and behavior of another class. The child class (or subclass) inherits all the attributes and methods of the parent class (or superclass). Example of Inheritance class ElectricCar(Car): def __init__(self, color, model, year, battery_capacity): super().__init__(color, model, year) self.battery_capacity = battery_capacity def charge(self): print("Charging
class Square(Rectangle): def __init__(self, side_length): super().__init__(side_length, side_length) We also define a honk method that prints "Honk