会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132647个问题

#coding=utf-8
import time
class CacheDecorator():
    __cache={}
    def __init__(self,func):
        self.func=func
    def __call__(self, *args, **kwargs):
        if self.func.__name__ in CacheDecorator.__cache:
            return CacheDecorator.__cache[self.func.__name__]
        else:
            value=self.func(*args,**kwargs)
            CacheDecorator.__cache[self.func.__name__]=value
            return value
def cost_time(func):
    def inner(*args,**kwargs):
        start=time.time()
        result=func(*args,**kwargs)
        end=time.time()
        print("耗时:","end-start")
        return result
    return inner
@cost_time
@CacheDecorator
def func1():
    print("start func1")
    time.sleep(3)
    print("end func1")

if __name__=="__main__":
    r1=func1()
    r2=func1()
    print(r1)
    print(r2)

老师,我照着文档敲了,但是真的看了好几遍视频都没看懂到底讲的啥意思

首先那个缓存到底是啥,最后执行也完全没体现出干了什么呀,还有这个为什么要搞一个字典在那里呀,我fun1那个函数都没有写return什么为什么它最后还会打印None,

CacheDecorator.__cache

CacheDecorator.__cache[self.func.__name__]

到底表示啥

value=self.func(*args,**kwargs)
CacheDecorator.__cache[self.func.__name__]=value

都是value,为什么后面那个value要在后面

return result

为什么加一个这句话


Python 全系列/第四阶段:函数式编程和核心特性/装饰器深入剖析 601楼
Python 全系列/第四阶段:函数式编程和核心特性/正则表达式 603楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637