我必须编写一个装饰器def
,该装饰器以validator def
作为参数。如果validator
返回了true
,它应该修饰main
来执行一些代码,如果返回了false
,它应该输出一个错误。
我试图用一个if语句在装饰器中编写两个def,以返回两个不同的def,但是它不起作用。
由于在线判断,功能和逻辑必须与我所说的完全一样(验证必须在装饰器外部进行)
这是一个例子:
#define decorator...
def validator(x):
return x>=0
@decorator(validator)
def f(x):
return x**0.5
print(f(4)) #should print 2
print(f(-4)) #should print error
答案 0 :(得分:0)
装饰词可以写为example
def hello_decorator(func):
def inner1(*args, **kwargs):
print("before Execution")
# getting the returned value
returned_value = func(*args, **kwargs)
print("after Execution")
# returning the value to the original frame
return returned_value
return inner1
# adding decorator to the function
@hello_decorator
def sum_two_numbers(a, b):
print("Inside the function")
return a + b
a, b = 1, 2
# getting the value through return of the function
print("Sum =", sum_two_numbers(a, b))
您可以将此代码重写为
def limit_decorator(func):
def internal(arg):
if (arg >= 0):
return func(arg)
else:
raise Exception("false input")
return internal
@limit_decorator
def square_root(a):
return a * 0.5
a = -5
print("Sum =", square_root(a))
答案 1 :(得分:0)
我建议在嵌套函数上使用一层来进行x的验证(基本上将验证器函数合并到装饰器中)
def deco(f):
def wrapper(x):
if x<=0:
return False
else:
return f(x)
return wrapper
@deco
def f(x):
return x**0.
f(1) #returns false
f(4) #returns 2.0
答案 2 :(得分:0)
尝试一下:
def decorator(validator):
def subdecorator(function):
def actual_function(arg):
if not validator(arg):
raise ValueError(f"Bad data: {arg}")
return function(arg)
return actual_function
return subdecorator
答案 3 :(得分:0)
这是您可以做的
#define decorator...
def validator(x):
return x>=0
def deco(validator):
def decorator(func):
def wrapper_decorator(*args, **kwargs):
if validator(*args, **kwargs):
return func(*args, **kwargs)
else:
print("error")
return
return wrapper_decorator
return decorator
@deco(validator)
def f(x):
return x**0.5
print(f(4)) #should print 2
print(f(-4)) #should print error
每个人都回答的答案基本上是正确的。但是,对于您的情况,您需要一个充当验证器的附加功能。因此,您可以添加另一个外部def
来接受验证器的功能,并检查其是否返回True / False。