为什么dir(x)中的所有名称对属性访问无效?

2024-05-19 15:05:35 发布

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

为什么程序员要把不能用于属性访问的东西塞进__dict__?例如,在我的Plone实例中,dir(portal)包含index_html,但是portal.index_html引发AttributeError。对于Products.ZCatalog.Catalog.mybrains__class__属性也是如此。为什么dir()不可信有什么好的理由吗?在

inspect模块中,我发现他们使用object.__dict__['x']而不是属性访问,因为他们不想触发getattr魔法。在


Tags: 实例index属性htmlplonedirdictclass
1条回答
网友
1楼 · 发布于 2024-05-19 15:05:35

我不知道普隆,所以以下是一般性的。在

dirthe docs

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

只是猜测一下,但我能想到两件事可能会发生

  • 对象有一个__dir__()方法,该方法返回它没有的属性

  • (不太可能)对象的具有您请求的属性(即,它在obj.__dict__或{}中,但重写__getattr__返回AttributeError

EDIT:python2.6+只支持__dir__,但是(不推荐使用的)特殊属性__methods__和{}可以用于早期版本。在

相关问题 更多 >