Discuss / Python / 交作业

交作业

Topic source

张康除

#1 Created at ... [Delete] [Delete and Lock User]

time.time()这个知识点没有讲过呀。。

def metric(fn):
    def decorator(*args,**kw):
        t1=time.time()
        fn(*args,**kw)
        t2=time.time()
        t=t2-t1
        print('%s executed in %s ms' % (fn.__name__, t))
        return fn(*args,**kw)
    return decorator

张康除

#2 Created at ... [Delete] [Delete and Lock User]

请教一下评论区:为什么把decorator函数的最后一行:return.....改为:return None,会显示测试失败?运行时间已经打印出来了,decorator的返回值并不影响metric函数的运行吧?

f = fast(11, 22)
s = slow(11, 22, 33)

运行fast和slow实际是在运行代理函数decorator,代理函数decorator return none的话,f和s的值均为none,测试必然失败,代理函数的返回结果必须与原函数一致

f = fast(11, 22)

为例

fast 是加装过metric装饰器的函数

传入metric的函数是下面描述的

def fast(x, y):

    time.sleep(0.0012)

    return x + y;

执行的主体是metric,原本的fast只是在metric里面的函数型参数

也就是说执行完metric,如果得不到任何结果,那么

@metric 的fast 也不会有任何结果

形象的说@的功能就是用metric吧 fast包装起来,然后metric是主体,然后metric可以用用到fast 也可以不用fast,取决于代码。

极端情况下比如下面这种形式,虽然接受传入任何参数,但是a函数本身不使用参数也是复合语法的。

def  a (*agrs,**kw):

     return 1


  • 1

Reply