Extending instead of Overriding in Python


Extending a method instead of Overriding it

In OOP, we have class inheritance. When we derive a class from an existing class, that derivation receives all the attributes of the parent class. Python has a solid design where performance and OOP is concerned, but there are a few gotchas, so look into the documentation before getting yourself in too deep.

One of the concerns that I ran into while doing a bit of socket programming has to do with a warning I noticed in the SocketServer documentation:

May be extended, do not override.

Fair enough. Obviously, we don't want to do things like overriding constructors for derived classes, but how do we go about extending a method instead of overriding it?

The first solution I found had to do with wrappers. Too complex and not very efficient. Don't go there, it will give you a headache.

The simple way of doing it is to simply override the method as you normally would (by adding a method of the same name in your derived class), and then calling the method from the base class.

Here's an example:

collapsehide line numbers
Sample Code
 1class Student():
 2 def __init__(self):
 3  enroll_in_school(self)
 4  self.enrolled=1
 5
 6class Driving_Student(Student):
 7 def __init__(self)
 8 Student.__init__(self)
 9 pay_for_parking(self)
Code ©SteveKallestad.com


Extending instead of Overriding in Python Commentary