1. 手写代码,不带参数
class Test(object):
def __init__(self, func):
print("初始化")
print("func name is %s" % func.__name__)
self.__func = func
def __call__(self, *args, **kwargs):
print("————————装饰器中的功能-——————-")
self.__func()
@Test
def test():
print("______test______")
test()
1.1 打印结果
C:\Users\HuJun\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/HuJun/PycharmProjects/pythonProject/daily_tesy/类装饰器.py
初始化
func name is test
————————装饰器中的功能-——————-
______test______
Process finished with exit code 0
2. 类装饰器,装饰器带参数
class Test(object):
def __init__(self, nums):
print("-----init------")
self.nums = nums
def __call__(self, func):
print("-----call------")
self.__func = func
return self.call_old_func
def call_old_func(self):
print("-----开始调用装饰器------")
self.__func()
print("-----结束调用装饰器------")
@Test(100)
def test():
print("-----test------")
test()
2.1 打印结果
C:\Users\HuJun\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/HuJun/PycharmProjects/pythonProject/daily_tesy/类装饰器2.py
-----init------
-----call------
-----开始调用装饰器------
-----test------
-----结束调用装饰器------
Process finished with exit code 0
|