Overriding and Super Functions
Learn how to override methods and what super function is in inheritance.
We'll cover the following
Inheritance is great for adding new behavior to existing classes, but what about changing behavior? Our Contact
class allows only a name and an email address. This may be sufficient for most contacts, but what if we want to add a phone number for our close friends?
Overriding method
We can do this easily by setting
a phone
attribute on the contact after it is constructed. But if we want to make
this third variable available on initialization, we have to override the __init__()
method. Overriding means altering or replacing a method of the superclass with a new method (with the same name) in the subclass. No special syntax is needed to do this; the subclass’s newly created method is automatically called instead of the superclass’s method, as shown in the following code:
Get hands-on with 1400+ tech skills courses.