Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Inheritance: Is it necessary to explicitly call the parents constructor and destructor?

I have some Code (for ev3dev):

class Motor(object):
    def __init__(self, portName):
        self.base = "/sys/class/tacho-motor/motor"
        self.number = self.getMotorNumberWithSpecificPortName(portName)
        self.name = self.base + str(self.number) + "/"

        self.setDefaultValues()

    def __del__(self):
        self.callReset()

    (...)

class TurnMotor(Motor):
    def __init__(self):
        super(TurnMotor, self).__init__("outA")

    def __del__(self):
        super(TurnMotor, self).__del__()

The goal is to define multiple motor classes like TurnMotor in this example who inherit from Motor and automatical __init__ with their specific port. They also should call the parents __del__ method on destruction to reset the motor.

I know that in this case I have to define a __init__ method for the subclass to initiate with the port I want but would the parents __del__ method still be called from the subclass if I leave out the definition for __del__ in the subclass?
Would this in general be possible for __init__ too?

Thanks in advance and sorry if this is a duplicate.

like image 538
monsterkrampe Avatar asked Mar 31 '16 11:03

monsterkrampe


2 Answers

__init__ and __del__ are merely construction and destruction hooks, although this statement can be subject to discussion.

What is important for the programmer is that you do not have to define the super-class con/desctructor. If you don't, Python looks for a con/destructor in the internal lookup chain, i.e. in the base class(es), according to the method resolution order (MRO).

If you want a con/destructor in the derived class and if you want to create or destroy instance variables of the super class (and most of the time you want to do that, as that is why you derived in the first place) or do whatever is done in the super classes con/destructor, then you will have to call the super classes methods accordingly.

This is not done explicitly because (a) Python gives you the chance of not doing it and (b) Python Zen says: "Explicit is better than implicit".

like image 190
steffen Avatar answered Sep 23 '22 15:09

steffen


Yes it is possible. If you do not overwrite a method within subclass the parent method will be invoked instead. This is also true for magic methods like __del__ or __init__.

Here a small example I run in python cli

>>> class A():
...    def __del__(self):
...       print('A.__del__')
... 
>>> class B(A): pass
... 
>>> b = B()
>>> del b
A.__del__

Class B will contain all information of class A mixed with its specific information.

like image 21
Nicolas Heimann Avatar answered Sep 25 '22 15:09

Nicolas Heimann