我正在阅读 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
。
这是一个基于您的代码的示例:
class ThinCrustPizza(Pizza):
pass
如果调用 ThinCrustPizza.prosciutto()
,您将获得 ThinCrustPizza
的实例,而不是它继承的基类 Pizza
方法从。这是因为 classmethod
中的 cls
将是您调用它的类,即子类。
但是,如果您调用 ThinCrustPizza.proscutto2()
,您将获得与在 Pizza
上调用它相同的 Pizza
实例,因为实现需要按名称引用 Pizza
。因为它没有获取传入的类,所以无法判断它是在子类上调用的。
关于python - 可以使用@staticmethod 替换@classmethod 并返回该类的实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56940509/