class Cat:
a=4
cat = Cat()
cat.__str__()
How come class Cat inherits the private functions __str__()
and __format__()
from object
?
Isn't the point of private functions that you cannot inherit them?
class Cat:
a=4
cat = Cat()
cat.__str__()
How come class Cat inherits the private functions __str__()
and __format__()
from object
?
Isn't the point of private functions that you cannot inherit them?
How come class Cat inherits the private functions
__str__()
and__format__()
from object?
To begin, these methods aren't actually private. Somewhat confusingly, python uses __varname
for private variables/methods, while __varname__
are not private, and can be considered magic methods or dunders, commonly used for operator overloading.
Isn't the point of private functions that you cannot inherit them?
Not quite. A __varname
private variable has the perception of not being inheritable:
class Foo:
def __foo(self):
print("foo")
def __init__(self):
self.__foo() # prints foo
class Bar(Foo):
def __init__(self):
super().__init__() # will print foo
self.__foo() # will error saying no __foo method
But, this is merely due to python's double underscore name mangling. __foo
in a class Foo
becomes _Foo__foo
, and it is inherited to Bar
, but it keeps its Foo
prefix. So, when you try to call __foo
from Bar
, it'll be mangled into _Bar__foo
, which doesn't exist. If you replaced the self.__foo()
line in Bar
with self._Foo__foo()
, then there would be no errors, and you'd be calling a "private" property.
See also:
There is no public
or private
things in python. Everything is accessible from everywhere.
But there are naming conventions that indicates if the user should use or access members. See the python.org section