Python中的静态方法和类方法有什么区别?

时间:2020-05-01 18:25:50

标签: python class static

我绝对理解Python中实例方法与类/静态方法之间的区别。有时,您不希望对象的实际实例执行某些操作。也许正在获取存储在所有实例中的某些信息。但是,我终生无法理解类和静态方法之间的区别。

我知道类方法采用一个类参数(通常为cls),它引用当前类。然后,静态方法无需接受任何参数。但是,我在网上看到的唯一主要区别是类方法有权访问/更改“类状态”。对于什么是“类状态”,我找不到很好的解释。

这是我用下面的输出运行的一些代码。

class Person:
    SPECIES = "homo sapien"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name} is {self.age} years old"

    def get_species(self):
        print(f"species: {Person.SPECIES}")

    def change_species_instance_method(self):
        Person.SPECIES="homo sapien (instance)"

    @classmethod
    def change_species_class_method(cls):
        cls.SPECIES="homo sapien (class)"

    @staticmethod
    def change_species_static_method():
        Person.SPECIES="homo sapien (static)"

me = Person("Kevin", 20)
sam = Person("Sam", 20)

me.get_species()
sam.get_species()

me.change_species_instance_method()
print()

me.get_species()
sam.get_species()

me.change_species_class_method()
print()

me.get_species()
sam.get_species()

me.change_species_static_method()
print()

me.get_species()
sam.get_species()

输出

species: homo sapien
species: homo sapien

species: homo sapien (instance)
species: homo sapien (instance)

species: homo sapien (class)
species: homo sapien (class)

species: homo sapien (static)
species: homo sapien (static)

因此,如果类方法和静态方法都可以修改类变量(在这种情况下为SPECIES),那么除了需要cls的类方法的定义之外,它们之间还有什么区别?谢谢!

另外,人们说过的另一个区别是类方法用于创建类的新实例,但是我也可以使用static来做到这一点。那么对于我正在编写的相对复杂的代码(即没有类继承)而言,静态方法和类方法之间在功能上有什么区别吗?

0 个答案:

没有答案