Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can virtual function be private in Python

Tags:

python

I want need a virtual mechanism in Python and was implemented as below:

class A() :
    def __init__(self) :
        self.level()

    def level(self) :
        print("At level A")

class B(A)
    def level(self) :
        print("At level B")

It worked as expected:

>>>b = B()
At level B

Then I wanted to keep level() function in private by changing function's name into __level():

class A() :
    def __init__(self) :
        self.__level()

    def __level(self) :
        print("At level A")

class B(A)
    def __level(self) :
        print("At level B")

But it didn't work:

>>>b = B() 
At level A

The virtual mechanism magically lost when the function became private! Can someone help to explain why?

like image 679
K Lamb Avatar asked Dec 21 '25 11:12

K Lamb


1 Answers

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling.

Private Variables

class A() :
    def __init__(self) :
        self.__level()
        self._B__level()

    def __level(self) :
        print("At level A")

class B(A):
    def __level(self) :
        print("At level B")

In [228]: b=B()
At level A
At level B

Due to this mangling, the B version of __level can't be used from A methods (even if they are inherited by a B object). It has to use the mangled name explicitly. Breaking this 'virtual' function link (as you call it) is the purpose of mangling, as stated in the above clip.

In [232]: b._A__level()
At level A
In [233]: b._B__level()
At level B
In [234]: b.__level()
....
AttributeError: 'B' object has no attribute '__level'
like image 56
hpaulj Avatar answered Dec 23 '25 01:12

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!