python 装饰器

python 装饰器

  1. 装饰器

    1
    2
    * 可以包装函数,类的"函数"
    * 装饰器本质 接收一个函数对象(可调用对象),返回一个可调用对象(返回的是在装饰器中定义的函数)
  2. 包装函数的装饰器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65

    //示例2:
    [root@dev test]# cat decol2.py
    #!/usr/bin/env python
    # coding: utf-8

    def deco(F): # 定义装饰器,装饰器是特殊的函数. F表示可调用对象
    def new_F(a,b): # 定义一个新的函数
    print("input",a,b) # 打印a和b
    return F(a,b) # 返回传入"函数可调用对象",并将a和b,传入到可调用对象
    return new_F # 返回这个定义的函数对象,类似闭包

    # 计算平方和
    @deco # 采用装饰器,在函数定义之前
    def square_sum(a,b):
    return a**2 + b**2

    # 计算平方差
    @deco
    def square_diff(a,b):
    return a**2 - b**2

    print(square_sum(3,4))
    print(square_diff(3,4))

    [root@dev test]# python decol2.py
    ('input', 3, 4)
    25
    ('input', 3, 4)
    -7


    示例3:
    [root@dev test]# cat decol3.py
    #!/usr/bin/env python
    # coding: utf-8

    # 新的装饰器
    def pre_str(pre=''):
    # 旧的装饰器
    def decorator(F):
    def new_F(a,b):
    print(pre + 'input' ,a,b)
    return F(a,b)
    return new_F
    return decorator

    # 计算平方和
    @pre_str(pre='hi + ')
    def square_sum(a,b):
    return a**2 + b**2

    # 计算平方差
    @pre_str(pre='hi - ')
    def square_diff(a,b):
    return a**2 - b**2

    print(square_sum(3,4))
    print(square_diff(3,4))

    [root@dev test]# python decol3.py
    ('hi + input', 3, 4)
    25
    ('hi + input', 3, 4)
    -7
  3. 包装类的装饰器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    [root@dev test]# cat decol4.py
    #!/usr/bin/env python
    # coding: utf-8

    def decorator(aClass):
    class newClass:
    def __init__(self,age):
    self.total_display = 0
    self.wrapped = aClass(age)
    def disply(self):
    self.total_display += 1
    print("total display",self.total_display)
    self.wrapped.display()
    return newClass

    @decorator
    class Bird:
    def __init__(self,age):
    self.age = age
    def display(self):
    print('My age is ',self.age)

    a = Bird(5)
    for i in range(3):
    a.disply()
    [root@dev test]# python decol4.py
    ('total display', 1)
    ('My age is ', 5)
    ('total display', 2)
    ('My age is ', 5)
    ('total display', 3)
    ('My age is ', 5)