python 3.6中平凡、原始、天真和乐观的钩子+
hooker的Python项目详细描述
自v5.0.0以来没有元类和类装饰器的微创钩子。
状态
- v3.10.1状态是Beta。
- v5.x状态是Pre-Alpha
我在生产中使用v3.10.1(https://pypi.org/project/hookery/3.10.1/)进行工作
此文档用于尚未准备好生产的v5.x
安装
pip install hookery==3.10.1
基本用法
fromhookeryimportHook,hooksclassProfile:on_activated=Hook()@on_activateddeflog_activation(self):print(f"Activating {self}")defactivate(self):hooks.trigger(self.on_activated)classWarehouseProfile(Profile):@Profile.on_activateddeflog_activation(self):print(f"Warehouse profile {self} is being activated")@Profile.on_activateddefanother_handler(self):print(f"This will also be printed")
上面的虚拟示例表明:
- 钩子注册不需要元类、基类和类装饰器。
- 您可以在同一个类中为每个钩子注册任意数量的处理程序
- 子类中名为log_activation的处理程序不会重写同名的处理程序 在父类中。
>>>profile=WarehouseProfile()>>>profile.activate()Activating<__main__.WarehouseProfileobjectat0x103ee66d8>Warehouseprofile<__main__.WarehouseProfileobjectat0x103ee66d8>isbeingactivatedThiswillalsobeprinted
限制
- 对我们来说,钩子和钩子处理程序是类规范的一部分。这意味着类不能有新的钩子 创建类后注册的已添加或新的钩子处理程序。如果要添加功能,您也可以 修改或扩展类。
- @classmethod和@staticmethod无法注册为处理程序,因为挂钩应用于 一个类,而不是类本身
- 最好不要用其他东西装饰处理器。