【发布时间】: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