@classmethod和@staticmethod在Python中是什么意思,它们有什么不同?我应该何时使用它们,为什么要使用它们,以及如何使用它们?

据我所知,@classmethod告诉一个类,它是一个应该继承到子类中的方法,或者。。。某物然而,这有什么意义?为什么不直接定义class方法而不添加@classmethod或@staticmethod或任何@定义?


当前回答

一种稍微不同的思考方式可能对某人有用。。。在超类中使用类方法来定义该方法在被不同的子类调用时的行为。当我们想要返回相同的东西而不管我们调用的子类是什么时,就使用静态方法。

其他回答

我是这个网站的初学者,我已经阅读了以上所有答案,并得到了我想要的信息。然而,我没有投票权。所以我想从StackOverflow开始,得到我所理解的答案。

@staticmethod不需要self或cls作为方法的第一个参数@staticmethod和@classmethod包装函数可以由实例或类变量调用@staticmethod修饰函数会影响某种“不可变属性”,子类继承无法覆盖其基类函数,该基类函数由@staticmethoddecorator封装。@classmethod需要cls(类名,如果需要,可以更改变量名,但不建议)作为函数的第一个参数@classmethod总是以子类的方式使用,子类继承可能会改变基类函数的效果,即@classmethod包装的基类函数可能会被不同的子类覆盖。

一个小汇编

@静态方法一种在类中编写方法的方法,而不引用它所调用的对象。因此不需要传递self或cls之类的隐式参数。它的编写方式与在类外部的编写方式完全相同,但在python中没有任何用处,因为如果您需要在类内部封装方法,因为该方法需要是该类的一部分,那么@staticmethod在这种情况下很方便。

@分类法当你想写一个工厂方法并且通过这个自定义属性可以附加在一个类中时,这一点很重要。可以在继承的类中重写此属性。

这两种方法的比较如下

简而言之,@classmethod将普通方法转换为工厂方法。

让我们用一个例子来探讨一下:

class PythonBook:
    def __init__(self, name, author):
        self.name = name
        self.author = author
    def __repr__(self):
        return f'Book: {self.name}, Author: {self.author}'

如果没有@classmethod,您应该一个接一个地创建实例,并且它们是分散的。

book1 = PythonBook('Learning Python', 'Mark Lutz')
In [20]: book1
Out[20]: Book: Learning Python, Author: Mark Lutz
book2 = PythonBook('Python Think', 'Allen B Dowey')
In [22]: book2
Out[22]: Book: Python Think, Author: Allen B Dowey

例如@classmethod

class PythonBook:
    def __init__(self, name, author):
        self.name = name
        self.author = author
    def __repr__(self):
        return f'Book: {self.name}, Author: {self.author}'
    @classmethod
    def book1(cls):
        return cls('Learning Python', 'Mark Lutz')
    @classmethod
    def book2(cls):
        return cls('Python Think', 'Allen B Dowey')

测试它:

In [31]: PythonBook.book1()
Out[31]: Book: Learning Python, Author: Mark Lutz
In [32]: PythonBook.book2()
Out[32]: Book: Python Think, Author: Allen B Dowey

看见在类定义中成功创建实例,并将它们收集在一起。

总之,@classmethoddecorator将传统方法转换为工厂方法,使用classmethods可以根据需要添加尽可能多的替代构造函数。

当他/她希望根据调用方法的子类来更改方法的行为时,可以使用@classmethod。请记住,我们在类方法中引用了调用类。

在使用静态时,您希望行为在子类之间保持不变

例子:

class Hero:

  @staticmethod
  def say_hello():
     print("Helllo...")

  @classmethod
  def say_class_hello(cls):
     if(cls.__name__=="HeroSon"):
        print("Hi Kido")
     elif(cls.__name__=="HeroDaughter"):
        print("Hi Princess")

class HeroSon(Hero):
  def say_son_hello(self):
     print("test  hello")



class HeroDaughter(Hero):
  def say_daughter_hello(self):
     print("test  hello daughter")


testson = HeroSon()

testson.say_class_hello() #Output: "Hi Kido"

testson.say_hello() #Outputs: "Helllo..."

testdaughter = HeroDaughter()

testdaughter.say_class_hello() #Outputs: "Hi Princess"

testdaughter.say_hello() #Outputs: "Helllo..."

一种稍微不同的思考方式可能对某人有用。。。在超类中使用类方法来定义该方法在被不同的子类调用时的行为。当我们想要返回相同的东西而不管我们调用的子类是什么时,就使用静态方法。