How do i use inheritance in python classes?
-
As the story goes; Congratulations!! you have just inherited a million dollars from a long-lost relative!
In a similar way, In python, a class can inherit its attributes from another class, the base class, also known as a parent or super class, can pass its attributes to the child class.
Note: Inheritance works from parent class to child class, but not the other way.
The code shows the Cake class, as the base class and the Bread class inherits from the Cake class. The ovenstart and ovenstop methods are not part of the Bread class, but because of inheritance, you can use them as part of the Bread class
class Cake(object): def __init__(self): print("You created the cake instance") def ovenstart(self): print("Oven started") def ovenstop(self): print("Oven stopped")
class Bread(Cake): def __init__(self): Cake.__init__(self) print("Ready, Steady, Bake!")
c1 = Cake() c1.ovenstart() c1.ovenstop() b1 = Bread() b1.ovenstart() b1.ovenstop()
Output from the c1 instance:
You created the cake instance
Oven started
Oven stoppedOutput from the b1 instance: Prints whatever was in Cake class and makes use of method from the Cake class.
You created the cake instance
Ready, Steady, Bake!
Oven started
Oven stopped
© Lightnetics 2024