【发布时间】:2017-06-16 18:42:29
【问题描述】:
我以前从未见过其他任何东西像这样工作。
还有什么可以做到这一点的吗?
>>> class NothingSpecial:
@classmethod
def meth(cls): pass
>>> NothingSpecial.meth
<bound method classobj.meth of <class __main__.NothingSpecial at 0x02C68C70>>
>>> NothingSpecial.__dict__['meth']
<classmethod object at 0x03F15FD0>
>>> getattr(NothingSpecial, 'meth')
<bound method NothingSpecial.meth of <class '__main__.NothingSpecial'>>
>>> object.__getattribute__(NothingSpecial, 'meth')
<classmethod object at 0x03FAFE90>
>>> type.__getattribute__(NothingSpecial, 'meth')
<bound method NothingSpecial.meth of <class '__main__.NothingSpecial'>>
【问题讨论】:
-
因为类方法是描述符。阅读描述符。
-
所以我看到位于描述符 how-to 上的类方法的纯 python 实现做同样的事情。所以我想这意味着如果
type.__getattribute__得到一个描述符,它正在做一些特别的事情。但我仍然不知道如何模仿这种行为。 -
type是一个元类,所有类的默认元类。它可能正在做一些特别的事情。 -
@bup:如果你想模仿它,你应该问一个单独的问题(也许解释你为什么要这样做)。
标签: python python-3.x class-method descriptor