You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中无需装饰器、继承或包装函数,如何实现多方法自动触发通用方法?

不使用装饰器/继承/包装函数的实现方案

可以利用Python的sys.settrace全局跟踪机制,在函数调用和返回的生命周期节点插入通用方法的执行逻辑,完全符合要求。

实现代码

import sys

def common_method():
    print("Common method called")

# 业务方法保持原始定义,无需任何修饰
def method1():
    print("Method 1 called")

def method2():
    print("Method 2 called")

# 定义跟踪函数
def trace_calls(frame, event, arg):
    # 只处理目标业务方法的调用和返回事件
    target_methods = {method1, method2}
    func = frame.f_code

    if event == 'call':
        # 检查当前调用的函数是否是目标方法
        for method in target_methods:
            if func is method.__code__:
                common_method()
                break
        return trace_calls  # 持续跟踪该函数的执行
    elif event == 'return':
        # 检查当前返回的函数是否是目标方法
        for method in target_methods:
            if func is method.__code__:
                common_method()
                break
    return None

# 启用跟踪
original_trace = sys.gettrace()
sys.settrace(trace_calls)

# 调用业务方法
method1()
method2()

# 恢复原始跟踪(可选,避免影响其他代码)
sys.settrace(original_trace)

运行输出

Common method called
Method 1 called
Common method called
Common method called
Method 2 called
Common method called

原理说明

  1. sys.settrace会为Python解释器设置一个全局跟踪钩子,每次函数调用、返回、异常等事件触发时,都会调用指定的跟踪函数。
  2. 跟踪函数trace_calls通过判断当前执行的函数代码对象(frame.f_code)是否匹配目标业务方法的代码对象,来精准触发前置/后置的common_method执行。
  3. 调用完成后恢复原始跟踪函数,避免对其他代码的执行造成不必要的影响。

内容的提问来源于stack exchange,提问作者Anik Mahmud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:40:07