【问题标题】:How to run a method before/after all class function calls with arguments passed?如何在所有传递参数的类函数调用之前/之后运行方法?
【发布时间】:2017-10-17 04:06:00
【问题描述】:

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

但是该解决方案不允许我们传递参数。

Catch "before/after function call" events for all functions in 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"

【问题讨论】:

    标签: python python-2.7 python-3.x metaprogramming


    【解决方案1】:

    所以我经过大量实验后想通了。

    基本上在元类'__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))
    

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

    【讨论】:

    • pretty 你可以在__getattribute__ 中轻松做到这一点,而无需引入元类。
    • 问题是我认为您无法使用 __getattribute__ 获取函数 args
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多