algN/test/语法/回调.py

40 lines
973 B
Python
Raw Normal View History

2025-08-23 10:12:26 +08:00
class TestClass(object):
def __init__(self):
self.fun = 0
def decorator(self, fun):
#通过fun变量实现对传入函数的回调
self.fun = fun
#仅注册回调函数,将原函数返回,不执行原函数工鞥呢,不改变原函数功能
return fun
def decorator1(self, type):
def wrapper(func):
if type == 'A':
self.fun_A = func
if type == 'B':
self.fun_B = func
return func
return wrapper
test = TestClass()
#将decorator_test函数传入test的decorator函数并执行decorator函数
@test.decorator
def decorator_test():
print('this is decorator_test')
@test.decorator1('A')
def decorator_test():
print('this is decorator_test A')
@test.decorator1('B')
def decorator_test():
print('this is decorator_test B')
#通过test的fun变量回调decorator_test函数
test.fun();
test.fun_A ();
test.fun_B ();