callable()
的语法是
callable(object)
callable() 参数
callable()
方法接受一个参数 object
。
callable() 的返回值
callable()
方法返回
True
- 如果对象看起来可调用False
- 如果对象不可调用。
请务必记住,即使 callable()
返回 True
,对该对象的调用仍可能失败。
但是,如果 callable()
返回 False
,对该对象的调用肯定会失败。
示例 1:callable() 如何工作?
x = 5
print(callable(x))
def testFunction():
print("Test")
y = testFunction
print(callable(y))
输出
False True
这里,对象 x 不可调用。而对象 y 看起来可调用(但可能不可调用)。
示例 2:可调用对象
class Foo:
def __call__(self):
print('Print Something')
print(callable(Foo))
输出
True
Foo
类的实例看起来可调用(在此情况下是可调用的)。
class Foo:
def __call__(self):
print('Print Something')
InstanceOfFoo = Foo()
# Prints 'Print Something'
InstanceOfFoo()
示例 3:对象看起来可调用但不可调用。
class Foo:
def printLine(self):
print('Print Something')
print(callable(Foo))
输出
True
Foo
类看起来可调用,但其实例不可调用。以下代码将引发错误。
class Foo:
def printLine(self):
print('Print Something')
print(callable(Foo)) # still returns True because Foo is a class (classes are callable)
InstanceOfFoo = Foo()
# Raises an Error
# 'Foo' object is not callable
InstanceOfFoo() # error occurs because instances of Foo are not callable
输出
True Traceback (most recent call last): File "", line 10, in TypeError: 'Foo' object is not callable
另请阅读