如何为Python抽象基类的选定函数实现自动执行的前后钩子?
可行,以下是实现方案
可以通过在父类Foo中重写__getattribute__方法,拦截对抽象方法的调用,自动检查并执行对应的pre_xxx和post_xxx钩子函数,无需在父类预先定义这些钩子。
实现代码
from abc import ABC, abstractmethod class Foo(ABC): @abstractmethod def bar(self): ... @abstractmethod def baz(self): ... def __getattribute__(self, name): attr = super().__getattribute__(name) # 仅针对指定的抽象方法做钩子包装 if name in ['bar', 'baz'] and callable(attr): def wrapped(*args, **kwargs): # 执行pre钩子(如果存在) pre_method = f"pre_{name}" if hasattr(self, pre_method): getattr(self, pre_method)() # 执行原方法 result = attr(*args, **kwargs) # 执行post钩子(如果存在) post_method = f"post_{name}" if hasattr(self, post_method): getattr(self, post_method)() return result return wrapped return attr # 子类示例 class FooChild(Foo): def pre_bar(self): print("执行pre_bar钩子") def bar(self): print("执行bar方法") def post_bar(self): print("执行post_bar钩子") def baz(self): print("执行baz方法") # 测试调用 foo_child = FooChild() foo_child.bar() # 输出顺序: # 执行pre_bar钩子 # 执行bar方法 # 执行post_bar钩子 foo_child.baz() # 输出:执行baz方法(无对应钩子,仅运行原方法)
说明
- 子类只需按需实现
pre_xxx或post_xxx方法,无需父类提前声明。 __getattribute__会拦截属性访问,这里仅针对bar、baz等指定方法做包装,避免影响其他属性。- 如果需要扩展到更多方法,只需修改
if name in ['bar', 'baz']中的方法名列表即可。
内容的提问来源于stack exchange,提问作者kennysliding
相关产品推荐
相关产品推荐

