简体   繁体   English

为什么可以从 python 中的 class object 继承私有函数

[英]why can you inherit private functions from class object in python

class Cat:
    a=4

cat = Cat()
cat.__str__()

How come class Cat inherits the private functions __str__() and __format__() from object ?为什么 class Cat 继承了object的私有函数__str__()__format__()

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? class Cat 怎么会继承 object 的私有函数__str__()__format__()

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.有点令人困惑的是,python 使用__varname作为私有变量/方法,而__varname__不是私有的,可以认为是魔术方法或 dunders,通常用于运算符重载。

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: __varname私有变量具有不可继承的感觉:

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 .但是,这仅仅是由于 python 的双下划线名称 mangling __foo in a class Foo becomes _Foo__foo , and it is inherited to Bar , but it keeps its Foo prefix. __foo Foo中的 __foo 变为_Foo__foo ,它继承到Bar ,但它保留其Foo前缀。 So, when you try to call __foo from Bar , it'll be mangled into _Bar__foo , which doesn't exist.因此,当您尝试从Bar调用__foo时,它将被破坏为不存在的_Bar__foo 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.如果您将Bar中的self.__foo()行替换为self._Foo__foo() ,则不会出现错误,并且您将调用“私有”属性。

See also:也可以看看:

There is no public or private things in python. python 中没有publicprivate的东西。 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请参阅python.org 部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM