[英]Issue creating decorator in Python3
Can anyone let me know what mistake i'm making. 谁能让我知道我在犯什么错误。
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: o / p:
Traceback (most recent call last): 追溯(最近一次通话):
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
looking to achieve something like this: 希望实现以下目标:
def decorator_with_args(decorator_to_enhance): 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 @decorator_with_args
def decorated_decorator(func, *args, **kwargs): 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) @decorated_decorator(42,404,1024)
def decorated_function(function_arg1, function_arg2): def装饰函数(function_arg1,function_arg2):
print("Hello {0} {1}".format(function_arg1, function_arg2))
decorated_function("Universe and", "everything") 装饰函数(“ Universe and”,“ everything”)
While you can wrap and function in another single function that does not return any callable object, bear in mind that the wrapped function is no longer callable. 虽然您可以在另一个不返回任何可调用对象的单个函数中进行包装和运行,但是请记住,包装后的函数不再可调用。 Thus, when timing objects that do not require reusability of the original object, then your current code works:
因此,在对不需要原始对象可重用性的对象进行计时时,当前代码可以正常工作:
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))
Output (without calling f2
): 输出(不调用
f2
):
'f2' took 8.988380432128906e-05s
However, if attempting to call f2
: 但是,如果尝试调用
f2
:
_ = f2()
Traceback (most recent call last): File "", line 1, in TypeError: 'NoneType' object is not callable
追溯(最近一次调用):TypeError中的文件“”,第1行:'NoneType'对象不可调用
To prevent the above error, create a wrapper function inside the decorating function: 为防止上述错误,请在装饰函数内部创建一个包装器函数:
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
will not be timed until it is called, triggering wrapper
: f2
直到被调用才被计时,触发wrapper
:
print(f2())
Output: 输出:
'f2' took 3.981590270996094e-05s
499500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.