如何访问python类中的魔术方法

2024-04-29 08:47:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解这一点。假设我们有这样一段代码

class Animal:
        def __init__(self, name, food):
                self.name = name
                self.__food = food
        def getFood(self):
                return self.__food

然后我们初始化它

>>> animal = {}
>>> animal["dog"] = Animal("rusty", "delicious thing you never know")

现在,在访问属性时,它似乎不允许我访问__food

>>> animal["dog"].name
'rusty'
>>> animal["dog"].__food
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Animal instance has no attribute '__food'

为什么失败了。我们可以清楚地看到,我使用的是self.__food = food,其中__是一种神奇的方法。那么如何打印__foodMagic属性呢?你知道吗


Tags: 代码nameselfreturn属性foodinitdef
1条回答
网友
1楼 · 发布于 2024-04-29 08:47:15

添加前导下划线的主要目的是提供类似于python中“私有变量”的内容。好吧,它们并不完全是私有变量——python并没有真正提供这种语言特性。解释器将损坏这些名称,使得从类外访问这些成员变得(稍微)困难。你知道吗

你可以阅读更多关于official documentation(2.x文档,因为你的问题是这样标记的)。相关摘录-

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

总之,“private”变量的损坏版本,比如__x,将是_ClassName__x。您可以验证您的类是否存在这种情况:

In [251]: animal['dog']._Animal__food
Out[251]: 'delicious thing you never know'

是的,所以,正如我在评论中提到的,“私有成员”的目的是使它不能在类外被访问。如果您定义这个成员的目的是为了在外部访问它,那么您甚至不应该添加前导下划线。你知道吗

相关问题 更多 >