在Python中,定义了__call__
方法的对象,就可以成为"可调用方法",即该函数可以被函数一样调用(简单的说,就是可以通过括号()的方法来调用对象)。
1__call__()
方法
1.1未定义__call__()
方法
class Student:
"""空测试类"""
pass
s1 = Student()
"""调用对象方法"""
s1()
运行结果:
Traceback (most recent call last):
File "/test.py", line 8, in <module>
s1()
TypeError: 'Student' object is not callable
程序说明:
因为类Student中没有__call__()
方法,属于不可调用,所以程序运行出现错误提示:TypeError: 'Student' object is not callable
.
1.2定义__call__
方法
class Student:
def __call__(self, *args, **kwargs):
"""定义call方法"""
print("call方法被调用")
s1 = Student()
s1()
运行结果:
call方法被调用
程序说明:
使用括号调用对象,本质上就是调用__call__()
方法,所以显示的内容,也是__call__()
方法执行的内容。
2判断可调用对象callable()
在python中,可以通过内置方法callable()
来判断一个对象是否是可调用的,返回布尔值。
方法定义:
def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
"""
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a
__call__() method.
"""
pass
示例代码:
class Class1:
"""空测试类"""
class Class2:
def __call__(self, *args, **kwargs):
"""定义call方法"""
pass
a1 = Class1()
print(callable(a1))
a2 = Class2()
print(callable(a2))
运行结果:
False
True
程序说明: 因为类Class1中没有定义__call__()
方法,所以示例对象a1属于不可调用,返回结果False,在类Class2中定义了__call__()
方法,所以示例对象a2属于可调用,返回True。
备注:
更多精彩博客,请访问:聂发俊的技术博客
对应视频教程,请访问:python400
完整markdown笔记,请访问: python400_learn_github
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。