Inheritance
In OOP I you defined a class from scratch every time. When two classes share a lot of behaviour, you can have one inherit from the other and reuse what is already there.
In OOP I you wrote each class on its own. When two classes share most of their behaviour, you can have one inherit from the other and reuse what is already there.
Pass the parent class in parentheses in the class header:
Here Dog is the subclass and Animal is the parent. The subclass picks up everything the parent has.
Attributes defined on the parent are available on the subclass instance:
What will be the output?
Methods are inherited the same way. The subclass can call any method the parent defines.
The describe method lives on the parent. The subclass uses it without redefining it:
What will be the output?
A subclass can also add its own methods on top of what it inherits. The parent stays untouched.
Dog inherits describe and adds a bark method of its own:
What will be the output?
Remember isinstance() from OOP I? It also returns True when you check against the parent class.
A Dog is also an Animal:
What will be the output?
What will be the output?
What will be the output?
What will be the output?