is_callable
Python callable(object) function returns True
if the object appears callable, otherwise it returns False
.
如果对象看起来可调用,Python callable(object)函数将返回True
,否则返回False
。
Python object is called callable if they define __call__()
function. If this function is defined then x(arg1, arg2, …) is a shorthand for x.__call__(arg1, arg2, …).
如果Python对象定义__call__()
函数,则称为可调用对象。 如果定义了此函数,则x(arg1,arg2,…)是x .__ call __(arg1,arg2,…)的简写。
Note that callable() function returns True if the object appears callable, it’s possible that it returns True even if the object is not callable. However, if this function returns False then the object is definitely not callable.
请注意,如果对象显示为可调用,则callable()函数将返回True,即使该对象不可调用,也有可能返回True。 但是,如果此函数返回False,则该对象绝对不可调用。
Also, a python class is always Callable. So always use callable() with an instance of the class, not the class itself. Let’s look at a simple example to check this behavior.
此外, python类始终是可调用的。 因此,请始终对类的实例而不是类本身使用callable() 。 让我们看一个检查此行为的简单示例。
class Person:
i = 0
def __init__(self, id):
self.i = id
p = Person(10)
print('Person Class is callable = ', callable(Person))
print('Person object is callable = ', callable(p))
Output:
输出:
Person Class is callable = True
Person object is callable = False
Let’s define a class with __call__() function.
让我们用__call __()函数定义一个类。
class Employee:
id = 0
name = ""
def __init__(self, i, n):
self.id = i
self.name = n
def __call__(self, *args, **kwargs):
print('printing args')
print(*args)
print('printing kwargs')
for key, value in kwargs.items():
print("%s == %s" % (key, value))
e = Employee(10, 'Pankaj') # creating object
print(e) # printing object
print(callable(e))
*args
is used to allow passing variable arguments to the __call__() function.
*args
用于允许将变量参数传递给__call __()函数。
**kwargs
is used to allow passing named arguments to the __call__() function.
**kwargs
用于允许将命名参数传递给__call __()函数。
Output:
输出:
<__main__.Employee object at 0x107e9e1d0>
True
Let’s look at some code snippets where we will use callable() to check if the object is callable, then call the instance as a function.
让我们看一些代码片段,我们将在其中使用callable()来检查对象是否可调用,然后将实例作为函数调用。
if callable(e):
e() # object called as a function, no arguments
e(10, 20) # only args
e.__call__(10, 20)
e(10, 20, {'x': 1, 'y': 2}) # only args of different types
e(10, 'A', name='Pankaj', id=20) # args and kwargs both
Output:
输出:
printing args
printing kwargs
printing args
10 20
printing kwargs
printing args
10 20
printing kwargs
printing args
10 20 {'x': 1, 'y': 2}
printing kwargs
printing args
10 A
printing kwargs
name == Pankaj
id == 20
That’s all for Python callable() and __call__() functions.
这就是Python callable()和__call __()函数的全部内容。
Reference: Official Documentation callable, Official Documentation call
参考: 可调用官方文档,可调用 官方文档
翻译自: https://www.journaldev.com/22761/python-callable-__call__
is_callable