python - 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
?谢谢!
此外,人们所说的另一个区别是类方法用于创建类的新实例,但我也可以使用静态方法来做到这一点。因此,对于我正在编写的代码的相对复杂性(即没有类继承),静态方法和类方法之间是否存在任何功能差异?
解决方案
推荐阅读
- php - 在使用 file_put_contents 使用 base 64 解码数据创建的 0 KB 的 Windows 临时文件中
- android - 定位 API 28 更新
- swift - 将工作分派到多个队列并同步等待
- r - 即使指定其他来源,ggmap 中的 Google API 密钥错误
- spring - Spring Cloud Gateway 增强来自外部 OAuth 授权服务器的 JWT 令牌
- docker - Docker 端口转发适用于 IPv6 但不适用于 IPv4
- r - 双条形图比较列
- android - 我是 Recyclerview 的新手。我想为每个底部导航视图项目显示 recyclerview。我该怎么做?
- php - 试图从 wp DB 中检索数据
- php - 在函数php中使用链接有什么区别?