装饰器 · staticmethod

0. 一句话定位

维度 内容
作用对象 类方法
使用场景 方法绑定
来源 标准库 builtins.staticmethod
语法形式 @staticmethod

1. 做什么

被装饰函数不接收自动绑定的 self/cls;可通过 Class.method()instance.method() 调用;无法直接访问类属性或实例属性(除非显式传参)。

2. 重点参数

参数 类型 默认值 作用 配置建议
无参装饰器 直接 @staticmethod

3. 最小可运行示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Dates:
def __init__(self, date):
self.date = date

def get_date(self):
return self.date

@staticmethod
def to_dash_date(date_str):
return date_str.replace("/", "-")

date = Dates("15-12-2016")
date_from_db = "15/12/2016"
date_with_dash = Dates.to_dash_date(date_from_db)

if date.get_date() == date_with_dash:
print("Equal")
else:
print("Unequal")
1
Equal

4. 常见变体

逻辑上属于类命名空间、但仅依赖参数的辅助函数,放在类内便于组织:

1
2
3
4
class MathUtil:
@staticmethod
def clamp(x, low, high):
return max(low, min(x, high))

5. 适用 / 不适用

适用

  • 函数语义上属于该类,但不需要 self/cls
  • 纯转换、校验等只依赖入参的工具方法

不适用

  • 需要访问或修改实例/类状态 → 实例方法或 @classmethod
  • 与类完全无关 → 模块级函数更清晰

6. 易踩坑

  • 静态方法内写 self.xxx 会报错(无 self);若需要实例数据应改为实例方法
  • 子类继承时静态方法不会自动获得多态的 cls 行为(与 classmethod 对比)

7. 近邻替代

替代 何时用
@classmethod 需要 cls、工厂方法、访问类属性
模块函数 与类组织无关

8. 参考

-------------本文结束感谢您的阅读-------------