用于检查条件

时间:2017-05-30 09:54:36

标签: python python-decorators

我尝试在装饰器的帮助下控制函数的评估。 所以我创建了一个MyClass的实例,然后根据mode属性适合的条件评估函数。

class MyClass:
    def __init__(self):
        self.mode = None

    def mode_handler(self, mode):
        def wrap(func):
            def inner(*args, **kwargs):
                if mode == self.mode:
                    return func(*args, **kwargs)
                else:
                    pass
            return inner
        return wrap

a = MyClass()


@a.mode_handler(mode='repeat')
def print_args(*args):
    print(args)


@a.mode_handler(mode='nuff_saif')
def nuff_said():
    print('NUFF SAID')

# 1
a.mode = 'nuff_said'
print_args(1, 2, 3)
nuff_said()

# 2
a.mode = 'repeat'
print_args(4, 5, 6)
nuff_said()

# 3
a.mode = 'something_else'
print_args(7, 8, 9)
nuff_said()

我希望得到

NUFF SAID
(4, 5, 6)

截至第1区mode=='nuff_said'和第2区mode=='repeat'

我得到了

(4, 5, 6)

代替。我应该如何改进我的代码?

2 个答案:

答案 0 :(得分:1)

问题在于你的模式处理程序本身:

@a.mode_handler(mode='repeat')
def print_args(*args):
    print(args)


@a.mode_handler(mode='nuff_saif') ### Here it is "nuff_saif"
def nuff_said():
    print('NUFF SAID')

# 1
a.mode = 'nuff_said' ### Here it is "nuff_said"
print_args(1, 2, 3)
nuff_said()

# 2
a.mode = 'repeat'
print_args(4, 5, 6)
nuff_said()

您可以编辑代码,然后它就可以了。欢呼声。

答案 1 :(得分:1)

你的代码中只有一个拼写错误。 nuff_said函数的装饰器使用模式nuff_sai f 但是在将函数调用到nuff_sai d 之前更改实例的模式。