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

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


当前回答

当他/她希望根据调用方法的子类来更改方法的行为时,可以使用@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..."

其他回答

一个小汇编

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

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

这两种方法的比较如下

@classmethod的意思是:当调用此方法时,我们将类作为第一个参数传递,而不是该类的实例(我们通常使用方法)。这意味着您可以在该方法中使用类及其财产,而不是特定的实例。

@staticmethod意味着:当调用此方法时,我们不会将类的实例传递给它(就像我们通常使用方法一样)。这意味着您可以将函数放在类中,但不能访问该类的实例(当您的方法不使用实例时,这很有用)。

类方法可以修改类状态,它绑定到类并且包含cls作为参数。

静态方法不能修改类状态,它绑定到类,它不知道类或实例

class empDetails:
    def __init__(self,name,sal):
        self.name=name
        self.sal=sal
    @classmethod
    def increment(cls,name,none):
        return cls('yarramsetti',6000 + 500)
    @staticmethod
    def salChecking(sal):
        return sal > 6000

emp1=empDetails('durga prasad',6000)
emp2=empDetails.increment('yarramsetti',100)
# output is 'durga prasad'
print emp1.name
# output put is 6000
print emp1.sal
# output is 6500,because it change the sal variable
print emp2.sal
# output is 'yarramsetti' it change the state of name variable
print emp2.name
# output is True, because ,it change the state of sal variable
print empDetails.salChecking(6500)

当他/她希望根据调用方法的子类来更改方法的行为时,可以使用@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..."

@分类法

@classmethod可以与__init__进行比较。你可以认为这是另一个__init__()。这是python在c++中实现类构造函数重载的方式。

class C:
    def __init__(self, parameters):
        ....

    @classmethod
    def construct_from_func(cls, parameters):
        ....

obj1 = C(parameters)
obj2 = C.construct_from_func(parameters)

注意,它们都有一个类的引用作为definitioin中的第一个参数,而init_使用self,但constructfrom_func使用cls。

@静态方法

@静态方法可以与对象方法进行比较

class C:
    def __init__(self):
        ....

    @staticmethod
    def static_method(args):
        ....

    def normal_method(parameters):
        ....

result = C.static_method(parameters)
result = obj.normal_method(parameters)