首先,__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
本文详细介绍了Python中__call__方法的使用,包括如何使类实例对象变得可调用,以及如何利用__call__和__init__方法实现装饰器。通过具体代码示例,展示了__call__在类实例化后的动态调用过程。
182

被折叠的 条评论
为什么被折叠?



