元类- hook技术
目录
元类的定义
class _AgentMeta(type):
"""The agent metaclass that wraps the agent's reply, observe and print
functions with pre- and post-hooks."""
def __new__(mcs, name: Any, bases: Any, attrs: Dict) -> Any:
"""Wrap the agent's functions with hooks."""
for func_name in [
"reply",
"print",
"observe",
]:
if func_name in attrs:
attrs[func_name] = _wrap_with_hooks(attrs[func_name])
return super().__new__(mcs, name, bases, attrs)
## 元类的使用
class AgentBase(StateModule, metaclass=_AgentMeta):
"""Base class for asynchronous agents."""
id: str
"""The agent's unique identifier, generated using shortuuid."""
supported_hook_types: list[str] = [
"pre_reply",
"post_reply",
"pre_print",
"post_print",
"pre_observe",
"post_observe",
]
"""Supported hook types for the agent base class."""
metaclass=_AgentMeta 表示:用 _AgentMeta 来创建 AgentBase 这个类
不写时,默认 metaclass 是 type(普通类都由 type 创建)
什么时候执行?
在定义类时(例如 import 这个模块时),Python 会:
把类体里的属性收集到 attrs 里
调用 _AgentMeta.new(mcs, "AgentBase", (StateModule,), attrs)
用返回的对象作为 AgentBase 类
也就是说,元类在“创建类”时运行,而不是创建实例时。
类比
entMe
普通情况:type 创建类 → 类创建实例元类情况:_AgentMeta 创建类 → 类创建实例
_AgentMeta 在创建 AgentBase 时,把 reply、print、observe 等方法用 _wrap_with_hooks 包了一层,所以这些方法会带 pre/post 钩子。
总结
metaclass=_AgentMeta 指定:创建 AgentBase 时使用 _AgentMeta 而不是默认的 type,从而在类创建阶段对方法做装饰(如加 hooks)。

浙公网安备 33010602011771号