zoukankan      html  css  js  c++  java
  • Python 类装饰器

    1.

    import time, datetime
    
    
    class Ly:
        def __init__(self, fun):
            self.fun = fun
            print('this is the first step on ' + str(datetime.datetime.now()))
            time.sleep(1)
            self.fun()
    
        def __call__(self):
            print('this is the thirty step on ' + str(datetime.datetime.now()))
            time.sleep(1)
    
    @Ly
    def show():
        print('this is the second step on ' + str(datetime.datetime.now()))
        time.sleep(1)
    
    if __name__ == "__main__":
        show()
        print('this is the fourth step on ' + str(datetime.datetime.now()))

    2.

    import time
    
    
    class Ly(object):
    
        def __init__(self, fun):
            print("this is the first step")
            time.sleep(1)
            self.fun = fun
    
        def __call__(self, *args):
            print("this is the second step")
            time.sleep(1)
            self.fun(*args)
            print("this is the fourth step")
            time.sleep(1)
    
    @Ly
    def show(a1, a2, a3, a4):
        print('this is the thirty step', a1, a2, a3, a4)
        time.sleep(1)
    
    
    show("parm", "1", "1", "1")
    print("After first part call")
    time.sleep(1)
    show("parm", "2", "2", "2")
    print("After second part call")

    从中可以发现:

    (1).只要有被类装饰器装饰的对象,类装饰器的 __init__ 函数就会执行(不需要调用)

    (2).被类装饰器装饰的函数不论被调用几次,__init__ 函数只会执行一次,并且它的执行是被装饰函数声明装饰时就自动执行,不需要手动调用

    (3).当被装饰函数存在参数时,从 __call__ 函数传进参数(不必须 *args,但这是一种规范 def __call__(self,*args,**kwargs))

         *args是指字符串,**kwargs是指字典

    3.

    import time
    
    class Ly:
        def __init__(self, one_parm, two_parm, three_parm):
            self.one_parm = one_parm
            self.two_parm = two_parm
            self.three_parm = three_parm
    
        def __call__(self, fun):
            print('性别为' + self.one_parm + "的" + self.two_parm + "岁的" + self.three_parm)
            time.sleep(1)
            def info(*args):
                fun(*args)
    
            return info
    
    
    @Ly("男", "22", "ly")
    def show(name, age, sex):
        print('性别为' + sex + "的" + age + "岁的" + name)
    
    
    show("蓝月", "20", "男")
    

    注意:

    (1).装饰器有装饰器的参数,函数(被装饰器修饰的函数)有函数的参数,不可混淆

    (2).的参数从 __init__ 函数中传,函数的参数从 __call__ 函数中传

    作者:蓝月

    -------------------------------------------

    个性签名:能我之人何其多,戒骄戒躁,脚踏实地地走好每一步

  • 相关阅读:
    Nacos 1.3.0版本部署连接mysql 8+
    Java Certificate证书问题
    UIKit之浅析UIButton
    Xcode Coule not launch "aaa" press launch failed:timed out waiting for app launch
    Cocos2d-x 安装教程for mac(Xcode)
    关于继承UITableViewController若干问题
    Table的分割线偏移量设置 及其 UIEdgeInset详解
    retain、strong、weak、assign区别
    iOS 使用xib创建cell的两种初始化方式
    No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=armv7 armv7s)
  • 原文地址:https://www.cnblogs.com/viplanyue/p/12700602.html
Copyright © 2011-2022 走看看