代码之家  ›  专栏  ›  技术社区  ›  nikow

ClassMethod对象是如何工作的?

  •  7
  • nikow  · 技术社区  · 15 年前

    我很难理解类方法对象在Python中是如何工作的,特别是在元类和 __new__ .在我的特殊情况下,当我遍历 members 被给予 新西兰 .

    对于普通方法,名称只存储在 __name__ 属性,但对于类方法,显然没有这样的属性。我甚至不知道如何调用ClassMethod,因为没有 __call__ 属性。

    有人能向我解释ClassMethod是如何工作的吗?或者能给我指一些文档吗?咕噜咕噜的声音什么也没有。谢谢!

    2 回复  |  直到 15 年前
        1
  •  18
  •   Matt Anderson    15 年前

    classmethod 对象是描述符。您需要了解描述符是如何工作的。

    简而言之,描述符是一个具有方法的对象 __get__ ,采用三个参数: self ,一个 instance 和一个 instance type .

    在正常属性查找期间,如果查找的对象 A 有一种方法 第二代 ,该方法将被调用,它返回的内容将替换为该对象。 .这就是当您对对象调用方法时,函数(也是描述符)如何成为绑定方法。

    class Foo(object):
         def bar(self, arg1, arg2):
             print arg1, arg2
    
    foo = Foo()
    # this:
    foo.bar(1,2)  # prints '1 2'
    # does about the same thing as this:
    Foo.__dict__['bar'].__get__(foo, type(foo))(1,2)  # prints '1 2'
    

    分类法 对象的工作方式相同。当它被发现时, 第二代 方法被调用。这个 第二代 类方法的方法,丢弃与 实例 (如果有)并且只经过 instance_type 当它呼唤 _获取__ 关于包装函数。

    说明性涂鸦:

    In [14]: def foo(cls):
       ....:     print cls
       ....:     
    In [15]: classmethod(foo)
    Out[15]: <classmethod object at 0x756e50>
    In [16]: cm = classmethod(foo)
    In [17]: cm.__get__(None, dict)
    Out[17]: <bound method type.foo of <type 'dict'>>
    In [18]: cm.__get__(None, dict)()
    <type 'dict'>
    In [19]: cm.__get__({}, dict)
    Out[19]: <bound method type.foo of <type 'dict'>>
    In [20]: cm.__get__({}, dict)()
    <type 'dict'>
    In [21]: cm.__get__("Some bogus unused string", dict)()
    <type 'dict'>
    

    有关描述符的更多信息可以在此处(以及其他位置)找到: http://users.rcn.com/python/download/Descriptor.htm

    用于获取由 分类法 :

    In [29]: cm.__get__(None, dict).im_func.__name__
    Out[29]: 'foo'
    
        2
  •  1
  •   Ewan Todd    15 年前

    This 好像有货。