Python: Overriding and Super methods

Inheritance in Python allows for a class to have access to the parent (super) class it is inheriting from. For example:

PhoneDialer:
   def __init__(self, number):
       self.number = number

We could have a child class called Caller, that inherits from PhoneDialer, like so:

Caller(PhoneDialer):
   def caller_dials(self):
       sip = sipp(self.number)

self.number was a value inherited from the Parent (super) class. If we wanted to override the Super class with more functionality it could be done in a messy way by calling the same values in the child class. In other words:

Caller(PhoneDialer):
   def __init__(self, number, audio_file):
       self.number = number
       self.audio_file = audio_file

The Caller class is overriding the Super class here… and setting number up with a potentially different value. If the goal was to add on to the parent class, this is messy because it requires more updates.

Instead we can make use of the super function like so:

Caller(PhoneDialer):
   def __init__(self, number, audio_file):
       super().__init__(number)
       self.audio_file = audio_file

The super function still references the result from the Parent (Super) class. This way if we maintain this, we still only update the variables/attributes (i.e. number) in one place.

With this combo in place, we can add on to the parent class, and still pull in the parent class values using the super() function.

Leave a Reply

Your email address will not be published. Required fields are marked *