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?

3
  • dunders(double underscore) aren't private functions, and python doesn't have truly private functions anyways. Commented Jan 2, 2021 at 23:10
  • 2
    Double underscores at the end also change (pronounced: remove) the name mangling. Commented Jan 2, 2021 at 23:11
  • dunder = __foo__ Commented Jan 2, 2021 at 23:14

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.