I'm rather new to class inheritance and need some assistance
I have a problem, where I want to override a parent class method, after it has been called from another inherited parent class method.
The basic concept looks something like this:
class Parent:
"""Parent class, that defines the logical workflow"""
def __init__(self):
pass
def outer_method(self):
# This method is called from the sub_classes
# everything in here is the same for all sub_classes
self.__inner_method(self)
def __inner_method(self):
# This method is called from self.outer_method()
# Everything in here will be handled differently by each sub_class
# And will therefore be overridden
pass
class Child(Parent):
"""Sub_class, that inherits from the Parent class"""
def __init__(self):
super().__init__()
def __inner_method(self):
# this should override Parent.__inner_method()
super().__inner_method()
print('Do some custom operations unique to this Sub_class')
The idea here is, that the Child
class calls outer_method
which then calls __inner_method
, which I want to be overridden by the child class.
But that doesn't work. When I run this script,
def main():
MyChild = Child()
MyChild.outer_method()
if __name__ == "__main__":
main()
what happens is that instead of calling Child.__inner_method()
, Parent.__inner_method()
is called.
How can I get the Child class to override the inner method of the parent class, after it has been called from the inherited outer method?
CodePudding user response:
The reason of the problem is the name you choose, python apply an special treatment to a class members if its name start with __
but doesn't end with that, called name mangling
, the reason it does that is in order to get python version of private variables/methods, so your __inner_method
got renamed to _Parent__inner_method
as result and any call to __inner_method
withing the parent class gets modify to be a call to this renamed method, and because the same happens to the child class its end with a _Child__inner_method
of it own which of course messed up with the inheritance mechanism if this isn't desired.
The solution is simple, rename all __inner_method
to _inner_method
.
A single _
is the convention for private stuff when you don't want the name mangling, with __
is for when you want it to be extra private if you will...