Python 数据模型:再次与 classmethod 混淆
据说:
当它产生一个类方法对象时,它会被转换为一个 绑定用户定义的方法对象,其 im_class 和 im_self 属性 都是C。
在 参考 中
,我做了一个 EX。
>>> class C(object) :
... @classmethod
... def cm(cls) : print cls
...
>>> C.cm
<bound method type.cm of <class '__main__.C'>>
>>> C.cm.im_self
<class '__main__.C'>
>>> C.cm.im_class
<type 'type'>
我不难理解这种现象。但不幸的是,在参考文献中,它告诉 im_self 应该与 im_class 相同。如何解释不一致的情况?
It's said that :
When it would yield a class method object, it is transformed into a
bound user-defined method object whose im_class and im_self attributes
are both C.
in the Reference
And I did an EX.
>>> class C(object) :
... @classmethod
... def cm(cls) : print cls
...
>>> C.cm
<bound method type.cm of <class '__main__.C'>>
>>> C.cm.im_self
<class '__main__.C'>
>>> C.cm.im_class
<type 'type'>
It's not hard for me to understand the phenomenon. But unfortunately, in the reference, it's told that im_self should be the same as im_class. How to explain the inconsistency?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我读到的和你一样。看来 Python 实际所做的并不完全是文档所说的。
它将
im_self
设置为类,将im_class
设置为类的类型,即它的元类。 Python 中类的默认元类是type
。这类似于绑定到实例的方法所发生的情况:im_self
是实例,im_class
是实例的类型。换句话说,在@classmethod
的情况下,类被视为实例(确实如此;它是type
的实例)。可能在没有更新文档的情况下改变了行为,或者文档一开始就是错误的。我以编写文档为生,我可以确认,对于 Python 大小的东西,几乎不可能保持 100% 正确——尤其是对于像这样的模糊细节。
Python 开发人员有一个报告文档中错误的程序。 尝试一下!
I read that the same way you do. It appears that what Python is actually doing is not exactly what the documentation says.
It sets
im_self
to the class, andim_class
to the class's type, i.e., its metaclass. The default metaclass for classes in Python istype
. This is analogous to what happens with methods that are bound to instances:im_self
is the instance andim_class
is the type of the instance. In the case of@classmethod
, in other words, the class is treated as the instance (which it is; it's an instance oftype
).Possibly the behavior was changed without the documentation being updated, or the documentation was just wrong to begin with. I write documentation for a living and I can confirm that it is almost impossible to keep it 100% correct for something the size of Python -- especially for obscure details like this one.
The Python developers have a procedure for reporting bugs in the documentation. Give it a try!