【问题标题】:Pre process arguments passed to all instance methods in Python传递给 Python 中所有实例方法的预处理参数
【发布时间】:2017-05-17 22:36:06
【问题描述】:
class SimpleClass(object):
     def A(self, *args):
          ...
     def B(self, *args):
          ...
     def C(self, *args):
          ...

是否有办法捕获传递给 A、B、C 的参数,修改这些参数并将修改后的参数传递给 A、B、C,而无需修改现有代码?

编辑:

答案:使用类装饰器,用另一个装饰器装饰类的所有方法。

方法装饰器执行预处理。

【问题讨论】:

标签: python class methods arguments preprocessor


【解决方案1】:

试试这个:

from types import FunctionType

class SimpleClass(object):
    def A(self, *args):
        pass
    def B(self, *args):
        pass
    def C(self, *args):
        pass


def methods(cls):
    """List of all method in class."""
    return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]

def args_decorator(method):
    """Decorator for SimpleClass methods"""
    def wrapper(self, *args):
        new_args = list(args)
        # change new_args here
        return method(self, *new_args)
    return wrapper


for method in methods(SimpleClass):
    setattr(SimpleClass, method, args_decorator(SimpleClass.__dict__[method]))

如果您可以更改您的SimpleClass,我建议您像这样使用装饰器:

def args_decorator(method):
    def wrapper(self, *args):
        new_args = list(args)
        # change new_args here
        return method(self, *new_args)
    return wrapper

class SimpleClass(object):
    @args_decorator
    def A(self, *args):
        pass
    @args_decorator
    def B(self, *args):
        pass
    @args_decorator
    def C(self, *args):
        pass

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 2020-07-29
    • 2015-06-11
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2023-03-30
    相关资源
    最近更新 更多