@classmethod的位置

use*_*501 10 python decorator python-2.7

位于python源代码中的decorator classmethod的源代码在哪里.具体来说,我无法找到它在2.7.2版中定义的确切文件

jsb*_*eno 20

我没有回答你的问题 - 但下面显示的是什么可能是一个装饰器等同于classmethod,用纯Python编写 - 因为源代码中的那个是在C中,内部Python-2.7.2/Objects/funcobject.c是Mishna提出的答案.

因此,类方法的思想是使用"描述符"机制,如Python的数据模型中所述 - 并使其成为__get__方法确实返回一个函数对象,在调用时,将使用第一个参数pre-调用原始方法填充:

class myclassmethod(object):
    def __init__(self, method):
        self.method = method
    def __get__(self, instance, cls):
        return lambda *args, **kw: self.method(cls, *args, **kw)
Run Code Online (Sandbox Code Playgroud)

在Python控制台上:

>>> class MyClass(object):
...     @myclassmethod
...     def method(cls):
...         print cls
... 
>>> 
>>> m = MyClass()
>>> m.method()
<class '__main__.MyClass'>
>>> 
Run Code Online (Sandbox Code Playgroud)

*编辑 - 更新*

OP进一步询问"如果我希望装饰器也接受一个参数,那将是init的正确格式?" -

在这种情况下,不仅__init__需要更改哪一个 - 接受配置参数的装饰器实际上在"两个阶段"中调用 - 第一个注释参数,并返回可调用 - 第二个调用只接受实际的函数装饰.

有几种方法可以做到 - 但我认为最直接的是有一个函数返回上面的类,如:

def myclasmethod(par1, par2, ...):
    class _myclassmethod(object):
        def __init__(self, method):
            self.method = method
        def __get__(self, instance, cls):
            # make use of par1, par2,... variables here at will
            return lambda *args, **kw: self.method(cls, *args, **kw)
    return _myclassmethod
Run Code Online (Sandbox Code Playgroud)


Mis*_*sev 13

tar -zxf Python-2.7.2.tgz
vim Python-2.7.2/Objects/funcobject.c

...
589 /* Class method object */
590 
591 /* A class method receives the class as implicit first argument,
592    just like an instance method receives the instance.
593    To declare a class method, use this idiom:
594 
595      class C:
596      def f(cls, arg1, arg2, ...): ...
597      f = classmethod(f)
598 
599    It can be called either on the class (e.g. C.f()) or on an instance
600    (e.g. C().f()); the instance is ignored except for its class.
601    If a class method is called for a derived class, the derived class
602    object is passed as the implied first argument.
603 
604    Class methods are different than C++ or Java static methods.
605    If you want those, see static methods below.
606 */
...
Run Code Online (Sandbox Code Playgroud)