Skip to main content
 首页 » 编程设计

python之classmethod除了把self改成cls还有什么作用

2025年04月02日8langtianya

有一个关于 classmethod 和 property 组合在一起的已回答问题:Using property() on classmethods

我还是不明白问题的原因,请帮忙。

我对classmethod的理解是,它只是将self替换为cls。考虑到这一点,我在过去几年写了几个类方法,现在我发现我一直都错了。

那么下面的代码中@classmethod和@cm有什么区别呢?

def cm(func): 
    def decorated(self, *args, **kwargs): 
        return func(self.__class__, *args, **kwargs) 
    return decorated 
 
class C: 
    V = 0  
 
    @property 
    @classmethod 
    def inc1(cls): 
        cls.V += 1 
        print("V1 =", cls.V) 
 
    @property 
    @cm  
    def inc3(cls): 
        cls.V += 3 
        print("V3 =", cls.V) 
 
c = C()  
#c.inc1  # fails with:  TypeError: 'classmethod' object is not callable 
c.inc3   # works 

inc3 与 cm 有效,但 inc1 与 classmethod 无效。

请您参考如下方法:

what is the difference between @classmethod and @cm from the code below?

装饰器在创建实例之前的类创建期间调用。

在你的例子中,由于@cm返回func(self.__class__, *args, **kwargs),它依赖于self,它应该被用作一个实例方法。

另一方面,@classmethod 可以在创建实例之前使用。

def cm(func): 
    def decorated(self, *args, **kwargs): 
        return func(self.__class__, *args, **kwargs) 
    return decorated 
 
class C: 
    @classmethod 
    def inc1(cls): 
        (blablabla) 
    @cm  
    def inc3(cls): 
        (blablabla) 
 
C().inc1() # works as a instance method 
C.inc1()   # works as a classmethod 
C().inc3() # works as a instance method 
C.inc3()   # TypeError: unbound method decorated() must be called with C instance as first argument (got nothing instead) 

对于类方法和属性的组合,可以通过返回自定义对象来完成。 Reference

class ClassPropertyDescriptor(object):    
    def __init__(self, f): 
        self.f = f 
    def __get__(self, obj, klass=None): 
        if klass is None: 
            klass = type(obj) 
        return self.f.__get__(obj, klass)() 
 
def classproperty(func): 
    if not isinstance(func, (classmethod, staticmethod)): 
        func = classmethod(func)     
    return ClassPropertyDescriptor(func) 
 
class C: 
    @classproperty 
    def inc1(cls): 
        (blablabla) 
 
C.inc1   # works as a classmethod property 

[编辑]

Q. What does the classmethod() call do with the method it decorates to achieve that?

可以使用descriptor 来实现。

class ClassMethodDescriptor(object):     
    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 
 
def myclassmethod(func): 
    return ClassMethodDescriptor(func)   
 
class C: 
    @myclassmethod 
    def inc1(cls): 
        (blablabla) 
 
C.inc1()   # works as a classmethod 

Q. Why is the result not callable?

因为ClassMethodDescriptor的实现没有定义__call__函数。一旦使用@property,它将返回不可调用的ClassMethodDescriptor。