python 学习:装饰器

import functools
#
# def func(message):
#     print('Got a message: {}'.format(message))


# 单个函数
def get_message(message):
    return 'Got a message: ' + message


# 函数嵌套,返回内部函数调用结果
def func(message):
    def get_message(message):
        print('Got a message: {}'.format(message))
    return get_message(message)


# 函数的参数是函数名
def root_call(func, message):
    print(func(message))


# 函数闭包:函数的返回值是函数对象
def func_closure():
    def get_message(message):
        print('Got a message: {}'.format(message))
    return get_message


# 函数赋值给变量,调用标量,等于调用函数
send_message = func
send_message_closure = func_closure()


# 装饰器函数, 带有不定数量的普通参数,key-name 参数
def my_decorator(func):
    @functools.wraps(func)  # 保留原函数的元信息:将原函数的元信息,拷贝到对应的装饰器函数里
    def wrapper(*args, **kwargs):
        print('wrapper of decorator')
        func(*args, **kwargs)

    return wrapper


# 带有自定义参数的装饰器函数
def repeat(num):
    def my_decorator(func):
        @functools.wraps(func)  # 保留原函数的元信息:将原函数的元信息,拷贝到对应的装饰器函数里
        def wrapper(*args, **kwargs):
            for i in range(num):
                print(f'{i+1}: wrapper of decorator')
                func(*args, **kwargs)

        return wrapper

    return my_decorator


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)


class MyDecorator(object):
    name = 'decorator of andy'

    def __init__(self):
        pass

    # my_decorator() 就是一个装饰器,它把真正需要执行的函数func包裹在其中,
    # 并且改变了它的行为,但是原函数func不变
    @staticmethod
    @my_decorator
    @Count
    def greet(message):
        print(message)

    # 装饰器 由内到外调用
    @classmethod
    @repeat(4)
    @Count
    def print_msg(cls, message):
        cls.show_cls_name()
        print(message)

    @classmethod
    def show_cls_name(cls):
        print(cls.name)


if __name__ == '__main__':
    print('decorator program start-----------')

    # send_message('hello world')
    # root_call(get_message, 'hello world')
    # func('hello world')
    # send_message_closure('hello,world')
    MyDecorator.greet('hello,world!')
    MyDecorator.print_msg('hello,world!')
    MyDecorator.print_msg('come on , andy!')
    print(MyDecorator.print_msg.__name__)

你可能感兴趣的:(python 学习:装饰器)