Python Inheritance - Is It Necessary To Explicitly Call The Parents Constructor and Destructor - Stack Overflow
Python Inheritance - Is It Necessary To Explicitly Call The Parents Constructor and Destructor - Stack Overflow
- Stack Overflow
9 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) + "/"
1
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?
__init__and __del__ are merely construction and destruction hooks, although this statement
7 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".
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__ .
10
Here a small example I run in python cli
Class B will contain all information of class A mixed with its specific information.