Python装饰器

Python 装饰器

闭包函数

定义:函数的返回值也可以是函数对象

def func1():
    def get_func(msg):
        print('传入参数: {}'.format(msg))
    return get_func

f1 = func1()
f1('hello world')

# 输出
传入参数:hello world

简单的装饰器

def my_decorator(funct):
    def wrapper():
        print('装饰器')
        funct()
    return wrapper
@my_decorator
def func1():
    print('Hello world')
func1()

#输出
装饰器
Hello world

带参数据装饰器

def my_decorator(func):
    def wrapper(msg):
        print('装饰器')
        func(msg)
    return wrapper


@my_decorator
def greet(msg):
    print(msg)


greet('hello world')

# 输出
装饰器
hello world

可以接收任何参数


def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('wrapper of decorator')
        func(*args, **kwargs)
    return wrapper

@my_decorator
def greet(msg):
    print(msg)


greet('hello world')

# 输出
装饰器
hello world

带自定义参数的装饰器

def repeat(num):
    def my_decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(num):
                print('wrapper of decorator')
                func(*args, **kwargs)
        return wrapper
    return my_decorator


@repeat(4)
def greet(message):
    print(message)

greet('hello world')

# 输出:
wrapper of decorator
hello world
wrapper of decorator
hello world
wrapper of decorator
hello world
wrapper of decorator
hello world

类装饰器

class Count:
    def __init__(self, func):
        self.func = func
        self.num_calls = 0

    def __call__(self, *args, **kwargs):
        self.num_calls += 1
        print('num of calls is: {}'.format(self.num_calls))
        return self.func(*args, **kwargs)

@Count
def example():
    print("hello world")

example()

# 输出
num of calls is: 1
hello world

example()

# 输出
num of calls is: 2
hello world

...

你可能感兴趣的:(python)