简体   繁体   English

如何在 Python 中为这个简单的函数编写装饰器?

[英]How can I write a decorator for this simple function in Python?

for example this is my function:例如这是我的功能:

def myfunc(x,y):
    print(x+y)

Now I want to write a decorator for it I want that decorator simply print "test" after x+y I mean I want next time I'm calling myfunc(x,y) I want results to be something like this现在我想为它编写一个装饰器我希望该装饰器在 x+y 之后简单地打印“test”我的意思是我希望下次我调用 myfunc(x,y) 我希望结果是这样的

x+y   
test

The reason I'm doing this is I want to learn passing a function with arguments to a decorator , if you write a decorator for this I will learn that in this simple example.我这样做的原因是我想学习将带参数的函数传递给装饰器,如果您为此编写装饰器,我将在这个简单的示例中学习。 Thanks for helping谢谢你的帮助

To make this work for a function with an arbitrary number of arguments you can do it this way:要使该函数适用于具有任意数量参数的函数,您可以这样做:

def print_test(func):
  def wrapper(*args,**kwargs):
    res = func(*args,**kwargs)
    print('test')
    return res
return wrapper

@print_test
def myfunc(x,y):
    print(x+y)

myfunc(2,3)

You can do it in this way:你可以这样做:

def mydecorator(f):
    def wrapper(x,y):
        print ("inside my decorator")
        f(x,y)
        print ("test")
    return wrapper

@mydecorator
def myfunc(x,y):
    print(x+y)

myfunc(4,5)

Output of above code execution is:上面代码执行的输出是:

inside my decorator
9
test

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

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