How to call a derived class method?

Ant*_*yak 4 python python-2.7

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
Run Code Online (Sandbox Code Playgroud)

I'm trying to use it like this, supposing that the overridden method to be called:

b = B()
b.public_method()
Run Code Online (Sandbox Code Playgroud)

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.

L3v*_*han 6

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
Run Code Online (Sandbox Code Playgroud)