Python中的callable是基于什么样的机制实现的
2016-07-12 21:07
525 查看
如题,在Python中有这样的方法callable,判断一个对象是否可以调用。
callable(object)
中文说明:检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。
看看源码
其中
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。
两个比较
结果为true
结果为false
callable(object)
中文说明:检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。
看看源码
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; } }
其中
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): pass oa = a() oa() callable(oa)
结果为true
class b: def _init__(self): pass ob=b() callable(ob)
结果为false
相关文章推荐
- Python动态类型的学习---引用的理解
- 从源码安装Mysql/Percona 5.5
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例