是否可以使用@staticmethod替换@classmethod并返回类的实例?

2024-06-28 16:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读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()

一个返回自己类的实例的静态方法可以代替类方法使用而没有任何缺点吗


Tags: 实例selfreturndefthisclshamclassmethod
1条回答
网友
1楼 · 发布于 2024-06-28 16:27:05

当只有一个类时,如您的示例中所示,classmethodstaticmethod(在实现中显式命名类)都可以工作。但是如果您希望将来能够扩展这个类,那么您可能需要使用classmethod

下面是一个基于您的代码的示例:

class ThinCrustPizza(Pizza):
   pass

如果调用ThinCrustPizza.prosciutto(),您将得到一个ThinCrustPizza的实例,而不是它从中继承方法的基类Pizza。这是因为cls中的classmethod将是您调用它的类,即子类

但是如果您调用ThinCrustPizza.proscutto2(),您将得到与在Pizza上调用它相同的Pizza实例,因为实现需要按名称引用Pizza。因为它没有得到传入的类,所以不能判断它是在子类上调用的

相关问题 更多 >