Decorator使函数返回None

时间:2016-12-29 09:57:22

标签: python python-2.7 python-3.x

我构建了两个函数来查找素数因子。一个版本比大数字上的另一个版本慢。我想评估这两个函数的运行时间。为此,我建立了一个装饰器来评估黯然失色的时间。 因为我插入装饰器,我的两个函数返回None。我的代码出了什么问题?

import math
import time

def time_usage(func):
    def wrapper(*args, **kwargs):
        beg_ts = time.time()
        func(*args, **kwargs)
        end_ts = time.time()
        print("[INFO] elapsed time: %f" % (end_ts - beg_ts))
    return wrapper

@time_usage
def find_factors(n):
    factors = []
    i = 2
    while i < n:
        while (n % i) == 0:
            factors.append(i)
            n /= i
        i += 1
    if n > 1:
        factors.append(n)
    return factors

@time_usage
def improved_prime_factor(n):
    factors = []
    # No need to test whether the number is divisible by any 
    # even number other than 2
    while n % 2 == 0:
        factors.append(2)
        n /= 2
    i = 3
    # If n = p * q, either p or q must be <= sqrt(n)
    max_factor = math.sqrt(n)
    while i <= max_factor:
        while n % i == 0:
            factors.append(i)
            n /= i
            # Update the upper band on possible factors
            max_factor = math.sqrt(n)
        i += 2
    if n > 1:
        factors.append(n)
    return factors

if __name__ == '__main__':
    print(improved_prime_factor(125556))  # return None
    print(find_factors(125556)) # return None

1 个答案:

答案 0 :(得分:7)

您需要返回func(*args, **kwargs)。使用wrapper

装饰functools.wraps方法也是一种很好的做法
import functools


def time_usage(func):       
    @functools.wraps
    def wrapper(*args, **kwargs):
        beg_ts = time.time()
        result = func(*args, **kwargs)   # save the result to a name
        end_ts = time.time()
        print("[INFO] elapsed time: %f" % (end_ts - beg_ts))
        return result # return the name
    return wrapper