Python 中的@classmethod 装饰器在内部做了什么?

What does @classmethod decorator in Python do internally?

我知道如何使用@classmethod 装饰器,但我想知道它在内部对它装饰的函数做了什么?它如何将调用它的 class/object 作为修饰函数的第一个参数传递给它?

谢谢

@class方法是一个Python描述符-Python 3, Python 2

您可以从对象或 class 调用装饰方法。

class Clazz:

    @classmethod
    def f(arg1):
        pass

o = Clazz()

如果您致电:

o.f(1)

它会被实际f(type(o), *args)调用。

如果您致电:

Clazz.f(1)

它会被实际f(Clazz, *args)调用。

在文档中,纯python class方法看起来像:

class ClassMethod(object):
"Emulate PyClassMethod_Type() in Objects/funcobject.c"

def __init__(self, f):
    self.f = f

def __get__(self, obj, klass=None):
    if klass is None:
        klass = type(obj)
    def newfunc(*args):
        return self.f(klass, *args)
    return newfunc