Inheritance in Object Oriented Programming is when child classes inherit common attributes from a “parent” class. For example, if you have a “parent” car_class. This class has attributes like price, color, weight, make, model etc.
You can create another child class called sedan_car_class. This sedan_car_class can inherit all the attributes of a car like price, color, weight, make, model, etc from the parent class without you having to define those attributes again in the secan_car_class.
#parent class class Car: def __init__(self, price, color, weight, make, model): self.car_price = price self.car_color = color self.car_weight = weight self.car_make = make self.car_model = model def discount(self, discount_amount): return self.car_price * (1-discount_amount) class Sedan(Car): # putting "Car" in parenthesis is showing that Sedan is INHERITING all the attributes in Car Class. def __init__(self, price, color, weight, make, model, shape): # attributes for this class Car.__init__(self, price, color, weight, make, model) # initialize all the attributes in Car_Class in here. self.car_shape = shape # the attribute specific to this particular class def discount(self, discount_amount): return self.car_price * (1-discount_amount/4)
You can also override any method defined in the Parent class inside the child class. For example, the discount method defined above.
One of the main benefits of Inheritance is that you can add methods and attributes to the
Car class and the
Sedan class will have access to those attributes and methods.