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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With