如何 运行 一个方法 before/after 所有 class 带有参数传递的函数调用?

How to run a method before/after all class function calls with arguments passed?

在 class 等问题中的每个方法之前 运行 有一些有趣的方法 Python: Do something for any method of a class?

然而,该解决方案不允许我们传递参数。

Catch "before/after function call" events for all functions in class 上有装饰器解决方案,但我不想回去装饰我所有的 classes。

有没有办法 运行 pre/post 操作依赖于每次调用对象方法时传递的参数?

示例:

class Stuff(object):
    def do_stuff(self, stuff):
        print(stuff)

a = Stuff()
a.do_stuff('foobar')
"Pre operation for foobar"
"foobar"
"Post operation for foobar"

经过大量实验,我想通了。

基本上在 metaclass' __new__ 中,您可以遍历 class' 命名空间中的每个方法,并换出正在创建的 class 中的每个方法运行 包含前逻辑、函数本身和后逻辑的新版本。这是一个示例:

class TestMeta(type):
    def __new__(mcl, name, bases, nmspc):
        def replaced_fnc(fn):
            def new_test(*args, **kwargs):
                # do whatever for before function run
                result = fn(*args, **kwargs)
                # do whatever for after function run
                return result
            return new_test
        for i in nmspc:
            if callable(nmspc[i]):
                nmspc[i] = replaced_fnc(nmspc[i])
        return (super(TestMeta, mcl).__new__(mcl, name, bases, nmspc))

请注意,如果您按原样使用此代码,它将 运行 init 和其他内置函数的 pre/post 操作。