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__ 函数中传

    作者:蓝月

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

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

  • 相关阅读:
    linux 静态库和动态库(共享库)的制作与使用(注意覆盖问题)转
    手机号码格式正则表达式
    项目去除TFS关联、迁移重部署
    Excel中VLOOKUP函数的用法和注意点
    自定义打赏插件
    分享一个无需注册,无次数限制的Smile聊天机器人接口
    TCP/IP
    Java字典树
    平衡二叉树结构 AVL
    二叉搜索树(二叉排序树)BST
  • 原文地址:https://www.cnblogs.com/viplanyue/p/12700602.html
Copyright © 2011-2022 走看看