class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def __call__(self, friend):
print('My name is %s...' % self.name)
print('My friend is %s...' % friend)
def my(self):
self('test')
# 对象的定义
p = Person('Bob', 'male')
# 第0种情况:通过 调用本身__call__()来执行
p.__call__('test')
print('--------------------')
# 第1种情况:通过 对象后加 括号 来调用__call__()
p('test')
print('--------------------')
# 第2种情况:通过 内部 self() 来调用 __call__()
p.my()
结果如下:
My name is Bob...
My friend is test...
--------------------
My name is Bob...
My friend is test...
--------------------
My name is Bob...
My friend is test...
本文介绍了Python中类的`__call__`方法的使用,展示了如何通过实例对象直接调用`__call__`,以及通过内部方法调用`__call__`的三种情况。示例代码创建了一个Person类,当对象被调用时,会打印出名字和朋友的名字。
1286

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



