简体   繁体   English

Python装饰器打印“无”

[英]Python decorator prints “none”

import random
import time

def timeit(func):

    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        print ("{} took {} secs \n".format(func.__name__, time.time() - start))
    return wrapper


@timeit
def insort(l):
    """ Uses insetion sort for sorting list """

    for i in range(1, len(l)): 
        temp = l[i]
        j = i
        while j > 0 and l[j - 1] > temp:
            l[j] = l[j - 1]
            j -= 1
            l[j] = temp
    return l


@timeit
def bublesort(l):
    """ Uses insetion sort for sorting list """

    for i in range(len(l)-1, 0, -1):
        for j in range(i):
            if l[j] > l[j+1]:
                l[j], l[j+1] = l[j+1], l[j]
    return l


x =random.sample(range(2000), 1000) 
print (insort(x[:]))
print (bublesort(x[:]))

Above code outputs: 上面的代码输出:

insort took 0.0629999637604 secs 

None
bublesort took 0.104000091553 secs 

None

Why it is printing none after every result and how can I prevent it? 为什么在所有结果后都不打印,我该如何防止呢? Also I am new to decorators so I would like to know if there is any better way for timing my code. 我也是装饰器的新手,所以我想知道是否有更好的方法来计时我的代码。

Your wrapper, which replaces the original function, ignores the return value and returns None . 您的包装器将替换原始函数,它将忽略返回值并返回None

Make the following change: 进行以下更改:

def timeit(func):

    def wrapper(*args, **kwargs):
        start = time.time()
        ret = func(*args, **kwargs)
        print ("{} took {} secs \n".format(func.__name__, time.time() - start))
        return ret
    return wrapper

This will make your decorator work properly. 这将使您的装饰器正常工作。 If you want to avoid printing the return values, change 如果要避免打印返回值,请更改

print (insort(x[:]))
print (bublesort(x[:]))

to just 只是

insort(x[:])
bublesort(x[:])

In general, if you don't want to print something, don't pass it to print . 通常,如果您不想打印某些东西,请不要将其传递给print

Why it is printing none after every result and how can I prevent it? 为什么在所有结果后都不打印,我该如何防止呢? Also I am new to decorators so I would like to know if there is any better way for timing my code. 我也是装饰器的新手,所以我想知道是否有更好的方法来计时我的代码。

It's printing the return value of wrapper (None) because of this: 由于以下原因,它正在打印包装器的返回值(无):

print (insort(x[:]))
print (bublesort(x[:]))

You are telling the interpreter to print the return value of these functions. 您正在告诉解释器打印这些函数的返回值。 If you don't want to see None then you should just call the functions: 如果您不想看到“ None ,则应调用以下函数:

insort(x[:])
bublesort(x[:])

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

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