在 Python 里,@staticmethod和@classmethod都是放在类里面的方法,但它们绑定对象不同。
1. 普通实例方法
最常见的是这种:
class User: def say_hello(self): print("hello")调用:
u = User() u.say_hello()这里的self表示当前对象实例。
也就是说,实例方法可以访问:
self.name self.age self.xxx适合处理和某个具体对象有关的数据。
2.@staticmethod:静态方法
class MathUtils: @staticmethod def add(a, b): return a + b调用:
print(MathUtils.add(1, 2))它的特点是:
@staticmethod def 方法名(...):不需要self,也不需要cls。
也就是说,它不关心当前对象是谁,也不关心当前类是谁。
它只是被放在类里面,起到一个“工具函数”的作用。
例如:
class FileUtils: @staticmethod def is_json_file(filename): return filename.endswith(".json")使用:
FileUtils.is_json_file("data.json")这种方法其实跟普通函数差不多,只是为了代码组织清晰,所以放到类里面。
适合场景:
这个函数逻辑上属于这个类, 但它不需要访问对象属性,也不需要访问类属性。3.@classmethod:类方法
class User: count = 0 @classmethod def get_count(cls): return cls.count调用:
print(User.get_count())它的特点是:
@classmethod def 方法名(cls, ...):第一个参数是cls,表示当前类本身。
它可以访问类属性:
cls.count cls.config cls.xxx也可以用来创建对象。
例如:
class User: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_dict(cls, data): return cls(data["name"], data["age"])使用:
data = {"name": "张三", "age": 18} user = User.from_dict(data) print(user.name) print(user.age)这里的from_dict就是一个典型的类方法。
它的作用是:根据字典数据创建一个User对象。
4. 三者区别总结
| 类型 | 第一个参数 | 能访问实例属性 | 能访问类属性 | 典型用途 |
|---|---|---|---|---|
| 实例方法 | self | 可以 | 可以 | 操作具体对象 |
| 静态方法 | 无 | 不可以 | 不直接访问 | 工具函数 |
| 类方法 | cls | 不可以直接访问 | 可以 | 操作类本身、创建对象 |
5. 通俗理解
可以这样记:
self:操作某一个具体对象 cls:操作这个类本身 staticmethod:只是放在类里的普通工具函数例如:
class Person: species = "human" def __init__(self, name): self.name = name def instance_method(self): print(self.name) @classmethod def class_method(cls): print(cls.species) @staticmethod def static_method(a, b): return a + b调用:
p = Person("张三") p.instance_method() # 用对象数据 Person.class_method() # 用类数据 Person.static_method(1, 2) # 普通工具函数简单说:
需要用对象数据 → 普通方法 self 需要用类数据 → @classmethod cls 谁的数据都不用 → @staticmethod