/* Test whether an object can be called */
int
PyCallable_Check(PyObject *x)
{
if (x == NULL)
return 0;
if (PyInstance_Check(x)) {
PyObject *call = PyObject_GetAttrString(x, "__call__");
if (call == NULL) {
PyErr_Clear();
return 0;
}
/* Could test recursively but don't, for fear of endless
recursion if some joker sets self.__call__ = self */
Py_DECREF(call);
return 1;
}
else {
return x->ob_type->tp_call != NULL;
}
}
ternaryfunc tp_call An optional
pointer to a function that implements
calling the object. This should be
NULL if the object is not callable.
The signature is the same as for
PyObject_Call(). This field is
inherited by subtypes.
从Python的源代码object.c:
上面写着:
__call__
属性。x
可调用iffx->ob_type->tp_call != NULL
^{} field 的说明:
您始终可以使用内置的
callable
函数来确定给定对象是否可调用;或者更好的方法是调用它并在稍后捕获TypeError
。callable
在Python 3.0和3.1中被删除,请使用callable = lambda o: hasattr(o, '__call__')
或isinstance(o, collections.Callable)
。例如,一个简单的缓存实现:
用法:
来自标准库、文件^{} 、内置
exit()
和quit()
函数的定义的示例:callable是一个对象,它允许您使用圆括号()并最终传递一些参数,就像函数一样。
每次定义函数时,python都会创建一个可调用对象。 例如,您可以通过以下方式定义函数func(它是相同的):
您可以使用这个方法而不是像doit或run这样的方法,我认为看到obj()比obj.doit()更清楚一些
可调用的就是任何可以调用的东西。
built-in callable (PyCallable_Check in objects.c)检查参数是否为:
__call__
方法的类的实例或名为
__call__
的方法是(according to the documentation)示例
相关问题 更多 >
编程相关推荐