Python中的callable是基于什么样的机制实现的

来源:互联网 发布:win7com端口 编辑:程序博客网 时间:2024/04/27 23:49

如题,在Python中有这样的方法callable,判断一个对象是否可以调用。

callable(object)
中文说明:检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

看看源码

intPyCallable_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;    }}

其中

int PyInstance_Check(PyObject *obj)
Return true if obj is an instance.
判断是否为一个对象

对于最后一个else中

ternaryfunc PyTypeObject.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.
指向函数的指针,用于callable检测

所以当用callable来检测一个类是否可调用,需要这个类有__call__,如果是一个方法,检测其tp_call。

两个比较

class a:    def __call__(slef):        passoa = a()oa()callable(oa)

结果为true

 class b:     def _init__(self):         pass ob=b() callable(ob)

结果为false

0 0