簡體   English   中英

在Python3中創建裝飾器的問題

[英]Issue creating decorator in Python3

誰能讓我知道我在犯什么錯誤。

裝飾器

import time

def f1(f):

    a = time.time()
    f()
    b = time.time()
    c = b-a
    print("time required is", c)
@f1

def f3(f2):

    n = []
    for i in range(1000):
        n.append(i)
    print(sum(n), "for F3")
    f2()

@f3

def f4():

    n = []
    for i in range(1000):
       n.append(i)
    print(sum(n), "for F4")

f4

o / p:

追溯(最近一次通話):

File "C:/test.py", line 13, in <module>

@f1

File "C:/test.py", line 7, in f1

f()

TypeError: f3() missing 1 required positional argument: 'f2'

Process finished with exit code 1

希望實現以下目標:

def decorator_with_args(decorator_to_enhance):

def decorator_maker(*args, **kwargs):

    def decorator_wrapper(func):

        return decorator_to_enhance(func, *args, **kwargs)

    return decorator_wrapper

return decorator_maker

@decorator_with_args

def裝飾的裝飾器(func,* args,** kwargs):

def wrapper(function_arg1, function_arg2):

    print("Decorated with {0} {1}".format(args, kwargs))

    return func(function_arg1, function_arg2)

return wrapper

@decorated_decorator(42,404,1024)

def裝飾函數(function_arg1,function_arg2):

print("Hello {0} {1}".format(function_arg1, function_arg2))

裝飾函數(“ Universe and”,“ everything”)

雖然您可以在另一個不返回任何可調用對象的單個函數中進行包裝和運行,但是請記住,包裝后的函數不再可調用。 因此,在對不需要原始對象可重用性的對象進行計時時,當前代碼可以正常工作:

import time
def timeit(f):
  c = time.time()
  _ = f()
  c2 = time.time()
  print(f"'{f.__name__}' took {c2-c}s")

@timeit
def f2():
  return sum(range(1000))

輸出(不調用f2 ):

'f2' took 8.988380432128906e-05s

但是,如果嘗試調用f2

_ = f2()

追溯(最近一次調用):TypeError中的文件“”,第1行:'NoneType'對象不可調用

為防止上述錯誤,請在裝飾函數內部創建一個包裝器函數:

def timeit(f):
 def wrapper(*args, **kwargs):
    c = time.time()
    _result = f(*args, **kwargs)
    c2 = time.time()
    print(f"'{f.__name__}' took {c2-c}s")
    return _result
 return wrapper

@timeit
def f2():
  return sum(range(1000))

f2直到被調用才被計時,觸發wrapper

print(f2())

輸出:

'f2' took 3.981590270996094e-05s
499500

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM