won*_*ton 6 python metaprogramming python-2.7 python-3.x
在诸如Python: Do Something for any method of a class? 等问题中,有一些有趣的方法可以在类中的每个方法之前运行方法。
然而,该解决方案不允许我们传递参数。
对于类中的所有函数,有一个关于捕获“函数调用之前/之后”事件的装饰器解决方案,但我不想返回并装饰我的所有类。
有没有一种方法可以运行依赖于每次调用对象方法时传递的参数的前/后操作?
例子:
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"
Run Code Online (Sandbox Code Playgroud)
所以我经过大量的实验才弄清楚。
基本上,在元类中,__new__您可以迭代类名称空间中的每个方法,并将正在创建的类中的每个方法替换为运行之前逻辑、函数本身和之后逻辑的新版本。这是一个示例:
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))
Run Code Online (Sandbox Code Playgroud)
请注意,如果您按原样使用此代码,它将运行init和其他内置函数的前/后操作。
| 归档时间: |
|
| 查看次数: |
5099 次 |
| 最近记录: |