7.2 类装饰器与内置装饰器:@property、@classmethod、@staticmethod 与 @lru_cache
本节目录
欢迎回到 HelloWorld 技术社区(www.helloworld.net) 《Python 现代开发实战》专栏。
除了自己手写装饰器,标准库内置的四大装饰器更是日常高频刚需:
@property:把方法伪装成属性访问,既能像user.age = -5这样优雅赋值,又能在底层触发合法性校验逻辑,无缝兼容旧代码的属性读取方式;@classmethod:第一个参数接收类本身cls,最常用于实现多态备选构造器(如User.from_json(raw_str)、Date.from_timestamp(ts));@staticmethod:不接收self也不接收cls,纯粹为了命名空间内聚而挂载在类下的工具函数;@functools.lru_cache(maxsize=128):一行代码为纯函数加上内存级 LRU(最近最少使用)结果缓存,瞬间消灭重复计算或高频配置查询。
from functools import lru_cache
class Article:
def __init__(self, title: str, content: str) -> None:
self.title = title
self._content = content
@property
def summary(self) -> str:
"""动态计算只读摘要属性"""
return f"{self._content[:30]}..."
@classmethod
def from_markdown(cls, md_text: str) -> "Article":
"""备选工厂构造器:从 Markdown 文本首行自动提取标题"""
lines = md_text.strip().splitlines()
title = lines[0].lstrip("# ").strip()
return cls(title=title, content="\n".join(lines[1:]))
@lru_cache(maxsize=256)
def get_system_setting(key: str) -> str:
print(f"首次查询数据库配置: {key}")
return f"value_of_{key}"
💬 HelloWorld 社区实战打卡
为什么 @lru_cache 不能直接装饰接收 list 或 dict 作为参数的函数?如果非要缓存,该怎么改造参数?带 #Python专栏打卡 留言!