python装饰器问题


import time

def time_master(func):
    def call_func():
        print("开始")
        start = time.time
        func()
        stop = time.time
        print("结束")
        print(f"耗时 {(stop - start):.2f} 秒")
    return call_func

def myfunc():
    time.sleep(2)
    print("I love Python")

myfunc = time_master(myfunc)

myfunc()

结果:

开始
I love Python
结束
Traceback (most recent call last):
  File "C:/Users/37683/Desktop/111.py", line 19, in <module>
    myfunc()
  File "C:/Users/37683/Desktop/111.py", line 10, in call_func
    print(f"耗时 {(stop - start):.2f} 秒")
TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'builtin_function_or_method'

错误原因:stop和start行中time模块后面time函数忘记加括号