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 学习:装饰器
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 装饰器 类装饰器 装饰器还有一种特殊的语法就是类装饰器,就是通过定义一个类来装饰函数。 注意: 需要让类的实例对象...
- 装饰器 装饰器本质是一个python函数,它可以在让其他函数不需要任何代码变动的前提下增加额外的功能,装饰器的返回...
- 我是被什么蒙蔽了?无知?冲动?世俗?尘世?不认真?偏狭?苛刻?狭隘?自私?恐惧?压制强迫自己?自尊心?急躁?习惯?...