简体   繁体   English

Function 不打印,而不是打印我希望它在 Python 的装饰器中打印的内容

[英]Function prints none instead of printing what I want it to print in decorators in Python

I am studying on decorators in Python.我正在研究 Python 中的装饰器。 I was trying to use the decorators with arguments.我试图将装饰器与 arguments 一起使用。 I'm having a problem with the decorators.我的装饰器有问题。 I defined two inner function in the default decorator function.我在默认装饰器 function 中定义了两个内部 function。 It returns none when I use it as below:当我使用它时它没有返回,如下所示:

def prefix(write: bool = False):
    def thread(func):
        def wrapper(*args, **kwargs):
            t1 = Thread(target=func, args=args, kwargs=kwargs)
            t1.start()
            if write:
                print("write parameter is true.")
        return wrapper
    return thread


@prefix(write=True)
def something(x):
    return x + x


print(something(5))

As you see, I defined two different functions named prefix and something.如您所见,我定义了两个不同的函数,分别命名为 prefix 和 something。 If the write parameter is true, it prints the string.如果 write 参数为 true,则打印字符串。 But something function is printing "None" instead of printing 5 + 5.但是 function 正在打印“无”而不是打印 5 + 5。

What's wrong?怎么了?

Well, your wrapper() function doesn't have a return statement, so it will always return None .好吧,您的wrapper() function 没有 return 语句,因此它将始终返回None

Furthermore, how would you expect it to print 5 + 5 (or rather, the result thereof) when that may not have been computed yet, considering you're starting a new thread to do that and never do anything with the return value of func at all?此外,考虑到您正在启动一个新线程来执行此操作,并且永远不会对5 + 5的返回值做任何func有吗?

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

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