>Python has a more general concept of callable object, that is every object that can be called, which means applied on some data.
我在读一篇博客的时候看到这句话,作者认为Python对callable的概念是比较宽泛的,任何对象都可以被调用。这样说对么?如何理解?
Python的内建的callable()
函数可以用来检测是否能够调用,如果所有对象都可以call,那么为什么还有检测呢?
同意 @charliecui 说的 python的Object是一个泛型概念
。
对于文中的话,我理解是 python
中一切都是对象,这些对象都是 object
的实例,Python
创建对象是通过 type
方式,这个type
又有一个 __call__
方法,实现了这个方法,最终的对象就能被调用(callable
)。
大概意思就是这些对象通过技巧都是可以调用的,通过使这些对象可以调用来处理一些数据。
简单的用法就是类似 web
框架中的路由 (Router
), 使得 Router直接装饰,不需要额外的创建实例来创建对象,而是让自身就是一个可以调用的对象。
python
class Router(): def __call__(self): pass @Router('/index') def index(): pass
具体实现可以参考 可以参考 https://github.com/nod/tornroutes/blob/master/tornroutes/__init__.py
一个给 tornado
实现 router
的 decorator
见stackoverflow上有关python的callable的讨论http://stackoverflow.com/questions/111234/what-is-a-callable-in-python
python的Object是一个泛型概念,而不是特制类的对象,比如函数也可以是一个Object,类也可以是Object。你看下callable()的原型,定义在builtin.py中
def callable(p_object): # real signature unknown; restored from __doc__
"""
callable(object) -> bool
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances with a __call__() method.
"""
return False
仔细一看,这是英语断句的问题啊
english
Python has [a more general concept] of [[callable object], that is every [object that can be called, which means applied on some data]]
不是“每个对象都能被调用”,而是“callable object”是“所有能被调用的对象”,最后那个从句解释调用的概念是“被应用于数据”。
Python has a concept
Python has a more general concept
Python has a more general concept of callable object
Python has a more general concept of callable object, that is every object that can be called
Python has a more general concept of callable object, that is every object that can be called, which means applied on some data