10
votes
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?

2
Name mangling. Your call to self.__get() in B is really calling self._B__get(), which does not exist. Unless you want this behavior, don't use leading double underscores. - kindall
Check out what is the meaning of a single and a double underscore before an object name and some of the linked questions as there are some detailed explanations. - LinkBerest
Re your update: Because you are calling __get from a method defined in class A. That's perfectly legal in any language that supports the concept of private -- in fact that is the most common use case of private methods. - Dale Wilson

2 Answers

9
votes

Leading double underscore names are private (meaning not available to derived classes)

This is not foolproof. It is implemented by mangling the name. Python Documentation says:

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. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

Thus __get is actually mangled to _A__get in class A. When class B attempts to reference __get, it gets mangled to _B__get which doesn't match.

In other words __plugh defined in class Xyzzy means "unless you are running as class Xyzzy, thou shalt not touch the __plugh."

1
votes

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()