zoukankan      html  css  js  c++  java
  • 装饰器乱入用法

    def innter(name):
        def a(func):#func接收index调用的参数‘a’
            name()
        return a
    
    @innter#当innter后无参数时,会将index 函数传入innter函数的name中
    def index():
        print('index---->')
    
    index('a')#
    def innter(name):#name = 1
        def a(func):#func接收index函数
            def b():
                func()
            return b#将函数b作为a的值返回给index 执行index()相当于执行b()
        return a#将函数a的值返回
    
    
    @innter('1')#当innter有参数时,会将‘1’传入innter函数的name中
    def index():
        print('index---->')
    
    #index = innter('1')(index) = a(index) =b
    #func 会根据作用域找到是通过传参过来的,func = index
    # dic_cho['1']()#这种会将index函数保存到字典中 index()#这种调用需要3层装饰器函数
    #然而两层的装饰器且innter带参数,不需要调用便可以执行index,可将函数保存到字典中,然后调用
    res = {}
    def innter(name):#name = 1
        def a(func):#func接收index函数
           res ['name']= func
        return a#将函数a的值返回,执行a函数
    
    
    @innter('1')#当innter有参数时,会将‘1’传入innter函数的name中
    def index():
        print('index---->')
    res['1']()

    #inter('1')(index) = a(index)
    #res[name] =func
    #res['1'] = index

    import time 
    
    def deco(func):
        startTime = time.time()
        func()
        endTime = time.time()
        msecs = (endTime-startTime)*1000
        print('%s'%msecs)
        
    def myfunc():
        print('start myfunc')
        time.sleep(2)
        print('end myfunc')
        
    deco(myfunc)#调用方式改变了,为了不改变调用方式↓
    
    import time 
    
    def deco(func):
        def wrapper():
            startTime = time.time()
            func()
            endTime = time.time()
            msecs = (endTime-startTime)*1000
            print('%s'%msecs)
        return wrapper
    
    
    def myfunc():
        print('start myfunc')
        time.sleep(2)
        print('end myfunc')
        
    myfunc =deco(myfunc)
    #deco(myfunc) ==>执行这个函数会获得一个返回值wrapper ,myfunc = wrapper
    myfunc()
    
    
    
    import time 
    def deco(func):
        def wrapper():
            startTime = time.time()
            func()
            endTime = time.time()
            msecs = (endTime-startTime)*1000
            print('%s'%msecs)
        return wrapper
    
    @deco
    def myfunc():
        print('start myfunc')
        time.sleep(2)
        print('end myfunc')
        
    myfunc()

     更新

    def wapper(func):
        def inner(*args,**kwargs):
            return func(*args,**kwargs)
        return inner
    """
    1. 立即执行wapper函数,并将下面装饰的函数当做参数传递
    2. 将wapper函数返回值获取,在index赋值
        index = inner函数
    """
    @wapper
    def index():
        print('函数内容')
    
    # 实际执行的 inner函数,inner函数内部调用原函数
    index()
  • 相关阅读:
    Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
    Django的ORM操作
    RabbitMQ
    CentOS忘记用户名或者密码解决办法
    VUE-es6
    vue基础之命令
    爬虫框架:scrapy
    爬虫高性能相关
    MongoDB
    Beautifulsoup模块
  • 原文地址:https://www.cnblogs.com/kunixiwa/p/7353705.html
Copyright © 2011-2022 走看看