首先,__call__
方法
def func():
print('123')
func()
print(func())
#调用--->call---> 啥啥啥的不能call
123
123
None
对应的,类实例对象的调用,需要使用到__call__
特殊方法
class Student:
def __init__(self, name):
self.name = name
def __call__(self, classmate):
print('我的名字是%s, 我的同桌是%s' %(self.name, classmate))
stu = Student('小陈')
stu('小明')
我的名字是小陈, 我的同桌是小明
用类实现装饰器
通过__init__
和__call__
方法实现
class Test:
def __init__(self, func):
self.__func = func
def __call__(self, *args, **kwargs):
print('wrapper context')
print('before')
self.__func(*args, **kwargs)
print('after')
@Test
def show():
print('hello')
show()
wrapper context
before
hello
after