TypeError:wrapper()缺少1个必需的位置参数:“num”(python)

2024-09-29 21:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测试我的长函数的性能。但是当我运行我的程序时,我得到了这个错误

Traceback (most recent call last):
File "C:\Users\Gautham\Desktop\official.py", line 14, in <module>
  def long2(num):
File "C:\Users\Gautham\Desktop\official.py", line 8, in performance
  return wrapper()
TypeError: wrapper() missing 1 required positional argument: 'num'

这是我的密码:

from time import time
def performance(func):
      def wrapper(num):
            t1 = time()
            func(num)
            t2 = time()
            print("Totla Time = %s"%(t2-t1))
      return wrapper()
@performance
def long(num):
      for i in list(range(num)):
            print(i**12)

Tags: inpyreturntimedefperformancelinewrapper
2条回答

从时间导入时间 def性能(func): def包装器(数量): t1=时间() func(num) t2=时间() 打印(“总时间=%s”%(t2-t1)) 返回包装器 @演出 def long(num): 对于列表中的i(范围(num)): 打印(i**12) 长(4)

你快到了!问题是您返回的是执行该函数的wrapper()(由于没有向其传递参数而失败),而不是返回函数本身的wrapper

from time import time

def performance(func):
    def wrapper(num):
        t1 = time()
        func(num)
        t2 = time()
        print("Totla Time = %s"%(t2-t1))
    return wrapper

@performance
def long(num):
    for i in list(range(num)):
        print(i**12)

相关问题 更多 >

    热门问题