[英]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 中没有
public
或private
的东西。 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.