2
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?

v1z3
  • 137
  • 2
  • 9

2 Answers2

3

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:

Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

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

limserhane
  • 1,022
  • 1
  • 6
  • 17