废话不多说,直接撸代码
import functools
import time
# 1.普通装饰器
def logger(func):
def wrapper(*args, **kwargs):
print('开始处理。。。')
func(*args, **kwargs)
print('处理结束。')
return wrapper
# 2.带参数的装饰器
def say_hello(who):
def wrapper(func):
def deco(*args, **kwargs):
if who == "Python":
print(f'Hello, {who}')
elif who == "Java":
print(f'你好,{who}')
func(*args, **kwargs)
return deco
return wrapper
# 3.不带参数的类装饰器
class LoggerClass:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print(f'function {self.func.__name__} is running')
return self.func(*args, **kwargs)
# 4.带参数的类装饰器
class LoggerClassInfo:
def __init__(self, level='info'):
self.level = level
def __call__(self, func):
def wrapper(*args, **kwargs):
print(f'[{self.level}]: function {func.__name__} is running')
func(*args, **kwargs)
return wrapper
# 5.偏函数和类组合实现装饰器
class DelayFunc:
def __init__(self, duration, func):
self.duration = duration
self.func = func
def __call__(self, *args, **kwargs):
print(f'Waiting for {self.duration} seconds')
time.sleep(self.duration)
return self.func(*args, **kwargs)
def eager_call(self, *args, **kwargs):
print(f'Call without delay')
return self.func(*args, **kwargs)
def delay(duration):
return functools.partial(DelayFunc, duration)
# 6.装饰类的装饰器
instances = {}
def singleton(cls):
def get_instance(*agrs, **kwargs):
cls_name = cls.__name__
print(f'cls_name = {cls_name}')
if not cls_name in instances:
print(f'add {cls_name}')
instances[cls_name] = cls(*agrs, **kwargs)
return instances[cls_name]
return get_instance
@singleton
class User:
def __init__(self, name, age):
self.name = name
self.age = age
@delay(2)
# @LoggerClass
# @LoggerClassInfo('debug')
# @LoggerClassInfo('info')
# @say_hello("Java")
# @say_hello("Python")
# @logger
def Test():
print('func Test')
if __name__ == '__main__':
Test()
print(bool(User('小明', 20) == User('小花', 18)))