我正在阅读this tutorial关于@classmethod
和@staticmethod
,我不知道为什么有必要使用@classmethod
。我可以使用@staticmethod
并返回类的一个实例得到相同的结果,如下所示:
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod
def prosciutto(cls):
return cls(['mozzarella', 'tomatoes', 'ham'])
@staticmethod
def prosciutto2():
return Pizza(['mozzarella', 'tomatoes', 'ham'])
我想知道这两种实现之间是否有区别:
p = Pizza.prosciutto()
p1 = Pizza.prosciutto2()
一个返回自己类的实例的静态方法可以代替类方法使用而没有任何缺点吗
当只有一个类时,如您的示例中所示,
classmethod
或staticmethod
(在实现中显式命名类)都可以工作。但是如果您希望将来能够扩展这个类,那么您可能需要使用classmethod
下面是一个基于您的代码的示例:
如果调用
ThinCrustPizza.prosciutto()
,您将得到一个ThinCrustPizza
的实例,而不是它从中继承方法的基类Pizza
。这是因为cls
中的classmethod
将是您调用它的类,即子类但是如果您调用
ThinCrustPizza.proscutto2()
,您将得到与在Pizza
上调用它相同的Pizza
实例,因为实现需要按名称引用Pizza
。因为它没有得到传入的类,所以不能判断它是在子类上调用的相关问题 更多 >
编程相关推荐