首页 > 解决方案 > Python中的静态方法和类方法有什么区别?

问题描述

我绝对理解 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?谢谢!

此外,人们所说的另一个区别是类方法用于创建类的新实例,但我也可以使用静态方法来做到这一点。因此,对于我正在编写的代码的相对复杂性(即没有类继承),静态方法和类方法之间是否存在任何功能差异?

标签: pythonclassstatic

解决方案


推荐阅读