decorator可作用于函数和类,功能有两个:

  • Call proxy
  • Interface proxy

Function Decorator

语法:

1
2
3
4
5
@decorator
def F(arg):
    

F(99)

效果:

1
2
3
4
5
def F(arg):
    

F = decorator(F)
F(99)

Call proxy示例:

1
2
3
4
5
6
def decorator(F):
    # Process function F
    return F

@decorator
def func(): 

Interface proxy示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def decorator(F):
    def wrapper(*args):
        # Use F and args
        # F(*args) calls original function
    return wrapper

@decorator
def func(x, y):
    

func(6, 7)    # 6, 7 are passed to wrapper's *args

decorator class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class decorator:
    def __init__(self, func):
        self.func = func
    def __call__(self, *args):
        # Use self.func and args
        # self.func(*args) calls original function

@decorator
def func(x, y):
    

func(6, 7)

Class Decorator

语法与function decorator类似

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def decorator(cls):
    class Wrapper:
        def __init__(self, *args):
            self.wrapped = cls(*args)
        def __getattr__(self, name):
            return getattr(self.wrapped, name)
    return Wrapper

@decorator
class C:
    def __init__(self, x, y):
        self.attr = 'spam'

x = C(6, 7)
print(x.attr)

Decorator 参数

1
2
3
4
5
6
7
def decorator(A, B):
    # save or use A, B
    def actualDecorator(F):
        # Save or use function F
        # Return a callable: nested def, class with __call__, etc.
        return callable
    return actualDecorator