How to call a derived class method?
python, python-2.7
Solution
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
Problem
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.