检查条件的Python处理程序
我试图在装饰师的帮助下控制函数的求值。 因此,我创建了一个检查条件的Python处理程序,python,python-decorators,Python,Python Decorators,我试图在装饰师的帮助下控制函数的求值。 因此,我创建了一个MyClass的实例,然后在模式属性适合的条件下计算函数 class MyClass: def __init__(self): self.mode = None def mode_handler(self, mode): def wrap(func): def inner(*args, **kwargs): if mode == se
MyClass
的实例,然后在模式
属性适合的条件下计算函数
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)
在第一块模式=='nuff_said'
和第二块模式=='repeat'
我得到
(4, 5, 6)
相反。如何改进代码?问题在于模式处理程序本身:
@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()
你可以编辑你的代码,然后它就可以工作了。干杯。您的代码中有一个输入错误。
nuff\u的decorator说
函数的模式是nuff\u saif,但是在将函数调用为nuff\u said之前,您更改了实例的模式。我在这里假设您给出了您正在使用的确切代码。decorator的有趣用法