Classes and OOP II

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:

Python

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:

Python
Output

What will be the output?

Python

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:

Python
Output

What will be the output?

Python

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:

Python
Output

What will be the output?

Python

Remember isinstance() from OOP I? It also returns True when you check against the parent class.

A Dog is also an Animal:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python