Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double underscore in python

Tags:

python

class A(object):
    def __get(self):
        pass

    def _m(self):
        return self.__get()


class B(A):
    def _m(self):
        return str(self.__get())

print(A()._m())
print(B()._m())

Why print(A()._m()) prints None, but print(B()._m()) raises AttributeError: 'B' object has no attribute '_B__get'?

I thought that double underscore prevents method overriding.

UPDATE

You write that __get is private.

Then why does the following work?

class A(object):
    def __get(self):
        pass

    def _m(self):
        return self.__get()


class B(A):
    pass

print(A()._m())
print(B()._m())

Why does this code doesn't raise AttributeError and prints None two times?

like image 496
Andrew Fount Avatar asked Jul 24 '17 19:07

Andrew Fount


1 Answers

For __methodName() member function of class A:

  • To call this member function from outside of class A, you can only call _A__methodName() (trying to call __methodName() will generate an error)

  • To call this member function inside class A, you can use both _A__methodName() and __methodName()

like image 132
Zhihui Shao Avatar answered Sep 28 '22 09:09

Zhihui Shao