Override "private" method in Python

Consider a class with "private", for example:

class Foo(object):
    def __init__(self):
        self.__method()
    def __method(self):
        print('42')

When I try to subclass Fooand override the method __method, I can see that it Foo.__methodis still being called instead MoreFoo.__method.

class MoreFoo(Foo):
    def __method(self):
        print('41')

>>> MoreFoo()
42
<__main__.MoreFoo object at 0x7fb726197d90>

How can I override this method?

+5
source share
3 answers

The point of using the double-underscore naming convention is to prevent (by accident) subclasses that overlap the method.

If you still have to override it, someone made a serious class design mistake. You can do this by naming your object like this:

def _Foo__method(self):

( _Foo). .

'private', - , (def _method(self):).

, Python ; .

+16

mangling, . , ( _Foo__method).

, , Python, . , , Python .

+8

, - :

class MoreFoo(Foo):
    def _Foo__method(self):
        print('41')

.

__spam ( , , ) _classname__spam, classname - .

But the designers from the original class felt that you didn't need to do something like this, since it is difficult to override it with a subclass - this is the purpose of double underscores to start with:

Defining a name is useful for allowing subclasses to override methods without breaking the intraclass method calls.

+3
source

All Articles