在 Python 里,@staticmethod 和 @classmethod 都是放在类里面的方法,但它们绑定对象不同。

📅 2026/7/1 18:32:56
在 Python 里,@staticmethod 和 @classmethod 都是放在类里面的方法,但它们绑定对象不同。
在 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