面向对象设计模式 - Python中callable的理解?
怪我咯
怪我咯 2017-04-17 14:28:44
0
3
542
>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,那么为什么还有检测呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回覆 (3)
小葫芦

见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
    Ty80

    仔细一看,这是英语断句的问题啊

    englishPython 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

      黄舟

      同意 @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实现routerdecorator

        最新下載
        更多>
        網站特效
        網站源碼
        網站素材
        前端模板
        關於我們 免責聲明 Sitemap
        PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!