Python 数据模型:再次与 classmethod 混淆

发布于 2025-01-01 05:21:45 字数 605 浏览 3 评论 0原文

据说:

当它产生一个类方法对象时,它会被转换为一个 绑定用户定义的方法对象,其 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

徒留西风 2025-01-08 05:21:45

我读到的和你一样。看来 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, and im_class to the class's type, i.e., its metaclass. The default metaclass for classes in Python is type. This is analogous to what happens with methods that are bound to instances: im_self is the instance and im_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 of type).

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文