请帮助。如何编写此装饰器(如果验证器返回“ True”,则将验证器发送给func:
mylist[c(1, 2)][c(1,3)] <- 0
答案 0 :(得分:0)
您可以使用:
def validator(func):
def is_positive(x):
assert x>=0, "function {} wont work because x is negative".format(func.__name__)
return func(x)
return is_positive
@validator
def f(x):
return x**0.5
print(f(4)) #should print 2
print(f(-4)) #should print error
输出:
2.0
Traceback (most recent call last):
...
Exception: function f wont work because x is negative
答案 1 :(得分:0)
这是装饰器定义
def decorator(method):
def wrapper(func):
def inner_wrapper(x):
if method(x):
return func(x)
else:
raise Exception
return inner_wrapper
return wrapper
def is_positiv(x):
return x > 0
@decorator(is_positiv)
def f(x):
return x**0.5
以下是有关python(https://realpython.com/primer-on-python-decorators/)中的装饰器的一些文档
最诚挚的问候