如何在所有带有参数传递的类函数调用之前/之后运行方法? [英] How to run a method before/after all class function calls with arguments passed?
问题描述
There are some interesting ways to run a method before every method in a class in questions such as Python: Do something for any method of a class?
但是,该解决方案不允许我们传递参数.
However that solution doesn't let us pass arguments.
在>捕获" ;函数调用之前/之后类中所有函数的事件,但我不想回过头来装饰我所有的类.
There's a decorator solution on Catch "before/after function call" events for all functions in class but I don't want to have to go back and decorate all my classes.
是否有一种方法来运行前/后操作,该操作取决于为对象方法的每次调用传递的参数?
Is there a way to run a pre/post operation that's dependent on the arguments passed for every invocation of an object's method?
示例:
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"
推荐答案
因此,经过大量实验,我发现了这一点.
So I figured it out after a lot of experimentation.
基本上,在元类的__new__
中,您可以遍历类的名称空间中的每个方法,并用运行前逻辑,函数本身和后逻辑的新版本替换正在创建的类中的每个方法. .这是一个示例:
Basically in the metaclass' __new__
you can iterate through every method in the class' namespace and swap out every method in the class being created with a new version that runs the before logic, the function itself, and the after logic. Here's a sample:
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操作.
Note that if you use this code as is it will run the pre/post operation for init and other builtin functions as well.
这篇关于如何在所有带有参数传递的类函数调用之前/之后运行方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!