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()))

Python 类装饰器

 

 

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")

Python 类装饰器

 

从中可以发现:

(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", "男")

Python 类装饰器

 

 

注意:

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

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

上一篇:python接口自动化整体设计框架(基础-连接数据库模块)八


下一篇:Mybatis-04