Python callable()函數用法執行個體分析,pythoncallable

來源:互聯網
上載者:User

Python callable()函數用法執行個體分析,pythoncallable

本文執行個體講述了Python callable()函數用法。分享給大家供大家參考,具體如下:

python中的內建函數callable( ) ,可以檢查一個對象是否是可調用的 。

對於函數, 方法, 匿名函式式, 類, 以及實現了 _ _call_ _ 方法的類執行個體, 它都返回 True.

>>> help(callable)Help on built-in function callable in module __builtin__:callable(...) 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.

1》函數是可調用的

>>> def add(x,y):...  return x+y...>>> callable(add)True

2》類和類內的方法是可調用的

>>> class C:...  def printf(self):...   print 'This is class C!'...>>> objC=C()>>> callable(C)#類是可調用的,調用它們, 就產生對應的類執行個體.True>>> callable(C.printf)True>>> callable(objC.printf)True

3》實現了__call__()方法的類執行個體是可調用的

>>> class A:...  def printf(self):...   print 'This is class A!'...>>> objA=A()>>> callable(A) #類是可調用的,調用它們, 就產生對應的類執行個體.True>>> callable(objA) #類A沒有實現__call__()方法,因此,類A的執行個體是不可調用的False>>> class B:...  def __call__(self):...   print 'This is class B!'...>>> objB=B()>>> callable(B) #類是可調用的,調用它們, 就產生對應的類執行個體.True>>> callable(objB) #類B實現了__call__()方法,因此,類B執行個體是可調用的True

4》lambda運算式是可調用的

>>> f=lambda x,y:x+y>>> f(2,3)5>>> callable(f)True

其它的,像整數,字串,列表,元組,字典等等,都是不可調用的,如下:

>>> callable(2)False>>> callable('python')False>>> l=[1,2,3]>>> callable(l)False>>> t=(4,5,6)>>> callable(t)False>>> d={'a':1,'b':2}>>> callable(d)False

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.