我必须编写一个以validator def作为参数的装饰器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发布于 2019-08-07 20:11:24
以下是您可以执行的操作
#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。
发布于 2019-08-07 19:06:22
装饰器可以编写为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)) 发布于 2019-08-07 19:21:57
我建议对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.0https://stackoverflow.com/questions/57392755
复制相似问题