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

    作者:蓝月

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

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

  • 相关阅读:
    BAPI LIST
    如何设计折叠屏幕
    图形学习 Javascript 正则 regexper.com
    Javascript 的数据是什么数据类型?
    Javascript 严格模式下不允许删除一个不允许删除的属性
    Javascript 在严格模式下禁止指向 this
    指针自增学习
    Javascript 严格模式下几个禁忌
    笔记本设置 2K 显示屏 Intel HD Graphics 3000
    Javascript 在严格模式下不允许删除变量或对象
  • 原文地址:https://www.cnblogs.com/viplanyue/p/12700602.html
Copyright © 2011-2022 走看看