I have the following classes:
class A:
def __init__(self):
#base constructor implementation
pass
def __virt_method(self):
raise NotImplementedError()
def public_method(self):
self.__virt_method()
class B(A):
def __init(self):
A.__init__(self)
#derived constructor implementation
pass
def __virt_method(self):
#some usefull code here
pass
I'm trying to use it like this, supposing that the overridden method to be called:
b = B()
b.public_method()
But instead I'm getting NotImplementedError
(Am I doing something wrong or is it a Python (2?) problem? I know that Python 2 is deprecated and it is better to use Python 3, but for now I really have no choice.
This is due to name mangling. The __virt_method
will be renamed by Python internally to _A__virt_method
in the base class, and _B__virt_method
in the derived class:
Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, where classname is the current class name with leading underscore(s) stripped.
Rename the method to _virt_method
(only one underscore) and it will work:
class A:
def __init__(self):
# base constructor implementation
pass
def _virt_method(self):
raise NotImplementedError()
def public_method(self):
self._virt_method()
class B(A):
def __init(self):
A.__init__(self)
# derived constructor implementation
pass
def _virt_method(self):
# some useful code here
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With