Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override "private" method in Python

Consider a class with a "private" method such as:

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

When I try to subclass Foo and override method __method, it can be seen that Foo.__method is still called, instead of MoreFoo.__method.

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

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

What would be the way to override such a method?

like image 362
Ernest A Avatar asked Feb 15 '13 15:02

Ernest A


People also ask

Can I override private method Python?

You can do it still, by naming your object just so: def _Foo__method(self): where you prefix the method name with one more underscore and the defining classname (so in this case prefixed with _Foo ). The process of renaming methods and attributes with a double underscore is called private name mangling.

Can you override a private method?

You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it's not accessible there.

How do you override a method in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

Can you overload override a private method?

No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared.


1 Answers

The point of using the double-underscore name convention is to prevent subclasses from (accidentally) overriding the method.

If you have to override it anyway, someone made a serious class design error. You can do it still, by naming your object just so:

def _Foo__method(self):

where you prefix the method name with one more underscore and the defining classname (so in this case prefixed with _Foo). The process of renaming methods and attributes with a double underscore is called private name mangling.

If you want to define a 'private' method that is still overridable in a subclass, you generally stick to names with one underscore instead (def _method(self):).

Due to its dynamic nature, almost nothing in Python is truly private; with a little introspection almost anything can be reached.

like image 79
Martijn Pieters Avatar answered Sep 22 '22 12:09

Martijn Pieters