python- decorator deorator
decorator: the role of decorator is to add additional functionality to existing function or object
1, the decorator is essentially a Python function,
2, it allows other functions do not require any code changes add additional features premise,
3, decorator return value is a function object
4, use: with @
5, the general function decorators are named warpper ()
"" "
"""
初级装饰器
"""
def debug(func):
def wrapper(*args, **kwargs): # 指定宇宙无敌参数
print("[DEBUG]: enter {}()".format(func.__name__))
print( 'Prepare and say...',)
return func(*args, **kwargs)
return wrapper # 返回
@debug
def say(something):
print( "hello {}!".format(something))
"""
高级
1、基于类实现的装饰器
1、对象重载了__call__()方法,那么这个对象就是callable
"""
class logging(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print(
"[DEBUG]: enter function {func}()".format(
func=self.func.__name__))
return self.func(*args, **kwargs)
@logging
def say(something):
print(
"say {}!".format(something))
"""
高级 : 类+参数
1、构造函数里接受的就不是一个函数,而是传入的参数。通过类把这些参数保存起来。然后在重载__call__方法是就需要接受一个函数并返回一个函数
"""
class logging(object):
def __init__(self, level='INFO'):
self.level = level
def __call__(self, func): # 接受函数
def wrapper(*args, **kwargs):
print(
"[{level}]: enter function {func}()".format(
level=self.level,
func=func.__name__))
func(*args, **kwargs)
return wrapper # 返回函数
@logging(level='INFO')
def say(something):
print
"say {}!".format(something)
"""
1、内置的装饰器
1、内置的装饰器和普通的装饰器原理是一样的,只不过返回的不是函数,而是类对象
1、@property
2、@classmethod
"""