【问题标题】:Advantage of using @classmethod instead of type(self) in Python?在 Python 中使用 @classmethod 而不是 type(self) 的优势?
【发布时间】:2026-02-11 19:05:01
【问题描述】:

使用@classmethod(和cls)而不是type(self) 来实例化类有优势吗?

例如,一个抽象类包含一个普通方法,该方法在某些时候会实例化一个子类的实例,该子类的实例调用该方法。所以对type(self)(位于抽象基类中的方法内)的调用将是对子类的调用(我想,如果使用@classmethod,也会如此)。

class M(ABC):
    ...
    def simple_method(self):
        'Do stuff & return new instance'
        return type(self)()

    @classmethod
    def cls_method(cls):
        return cls()

class A(M):
    ...

a = A()
b = a.simple_method()
c = a.cls_method()

在我看来,使用type(self) 比使用@classmethod 更容易、更灵活。有什么反对这种做法或应该避免的情况吗?

【问题讨论】:

    标签: python class class-method


    【解决方案1】:

    在第一种情况下,您正在评估对象的类型,然后从中创建一个对象,这将比使用 classmethod 慢,因为 cls 直接传递给函数,无需评估类型。另一个区别是调用classmethod 不需要初始化该类的对象,您可以使用A.cls_method() 直接调用它

    【讨论】:

    • 认为type(self) 在计算上与self.__class__ 相同吗?调用类方法b = a.cls_method() 会比直接调用b = type(a)() 便宜吗?
    • type 和 class 有一些区别,最好在这里讨论*.com/questions/1060499/…,函数调用也会增加开销,*.com/questions/14648374/… a.cls_method() 更便宜就内存占用而言,因为您在内存中没有对象,因此创建对象需要一些时间,因此在时间方面也应该有所不同,但我们在这里谈论的是微优化,没什么意义