简体   繁体   English

我该如何编写随参数而变化的装饰器

[英]how can I write a decorator that changes with arguments

I have to write a decorator def that takes a validator def as argument. 我必须编写一个将validator def作为参数的装饰程序def If the validator returned true it should decorate main to execute some code and if it returned false it should print an error. 如果validator返回true ,则应修饰main以执行一些代码,如果返回false ,则应打印错误。

I have tried to write two def in decorator with an if statement to return two different defs but it is not working. 我试图用if语句在装饰器中编写两个def,以返回两个不同的def,但是它不起作用。

the functionality and the logic MUST be exactly like i said because of online judging (validation must be done outside of decorator) 由于在线判断,功能和逻辑必须与我所说的完全一样(验证必须在装饰器外部完成)

Here's an example: 这是一个例子:

#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

Decorators can be written as 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)) 

You can rewrite this code as 您可以将此代码重写为

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)) 

I would suggest to do the validation of x, using one layer on nested functions (basically merge the validator function into the decorator) 我建议对嵌套函数使用一层来进行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

Try this: 尝试这个:

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

Here is what you can do 这是你可以做的

#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

The answers everyone has answered are basically correct. 每个人都回答的答案基本上是正确的。 However for your case, you require an additional function that acts as a validator. 但是,对于您的情况,您需要一个充当验证器的附加功能。 Hence you can add in another outer def to take in the function of the validator and check if it returns True/False. 因此,您可以添加另一个外部def来接受验证器的功能,并检查其是否返回True / False。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM