callable()函數(shù)是Python的一個(gè)內(nèi)置函數(shù)。該函數(shù)判斷一個(gè)對(duì)象是否可被調(diào)用,如果傳遞給該函數(shù)的對(duì)象可被調(diào)用,則返回True,否則返回False。在實(shí)際中,即使該函數(shù)返回True,也有可能在調(diào)用該對(duì)象時(shí)會(huì)失敗,當(dāng)然,若該函數(shù)返回的是False,在調(diào)用該對(duì)象時(shí)絕對(duì)不會(huì)成功。
在Python類中如果定義了__call__()方法,則該類的實(shí)例是可調(diào)用的。
通俗地講,一般情況下用戶定義的方法/函數(shù)是可以調(diào)用的,但類的實(shí)例一般不能按照方法/函數(shù)的形式來調(diào)用,但如果類的內(nèi)部實(shí)現(xiàn)了__call__()方法,則該類的實(shí)例可以按照方法/函數(shù)的形式來調(diào)用。
注意:callable()函數(shù)在Python 3.0版本中被移除,又再3.2版本中重新添加了回來。
callable(object)
object:要判斷的對(duì)象或?qū)嵗?/p>
該函數(shù)的返回值是一個(gè)布爾值:True或False.
下面使用幾個(gè)實(shí)例來講解callable()方法的具體使用方法。
#函數(shù)
def fun():
print("調(diào)用fun()函數(shù)")
#創(chuàng)建一個(gè)對(duì)象
fun1 = fun
class test:
def __call__(self, *args, **kwargs):
print("定義了__call__()方法")
#創(chuàng)建類的實(shí)例
test_obj = test()
print("fun is callable?",callable(fun))
print("fun1 is callable? ",callable(fun1))
print("test is callable? ",callable(test))
print("test_obj is callable? ",callable(test_obj))
#調(diào)用試試
fun()
fun1()
test()
test_obj()
輸出結(jié)果:
fun is callable? True
fun1 is callable? True
test is callable? True
test_obj is callable? True
調(diào)用fun()函數(shù)
調(diào)用fun()函數(shù)
定義了__call__()方法
在上面的例子中,我們首先定義了一個(gè)函數(shù)fun(),然后定義了fun()函數(shù)的一個(gè)引用對(duì)象fun1;其次定義了一個(gè)類Test和類的一個(gè)實(shí)例test_obj,在類Test中實(shí)現(xiàn)了__call__()函數(shù);最后測(cè)試函數(shù)fun()、函數(shù)的引用fun1、類和類的對(duì)象test_obj的可調(diào)用性。從結(jié)果可以看出四個(gè)對(duì)象的callable()函數(shù)返回值都是True,并且調(diào)用都獲得了成功。
一般情況,在對(duì)象的可訪問范圍內(nèi),類和方法/函數(shù)本身總是可以調(diào)用的,但類的實(shí)例在未定義__call__()函數(shù)時(shí)則不能被調(diào)用。
下面的例子演示了callable()函數(shù)返回False的幾種情況:
n = 123
s = 'VeVb.com'
lst = ['R', 'Python', 'SPSS']
t = ('優(yōu)雅的代碼訂閱號(hào)','武林網(wǎng)')
d ={'K1':'V1','K2':'V2'}
class Student:
sid = 0
def __init__(self,sid):
self.sid = sid
stu = Student('001')
print("n is callable?", callable(n))
print("s is callable?", callable(s))
print('列表對(duì)象可調(diào)用?', callable(lst))
print('元組對(duì)象可調(diào)用?', callable(t))
print('字典對(duì)象可調(diào)用?', callable(d))
print('stu is callable?', callable(stu))
輸出結(jié)果如下:
n is callable? False
s is callable? False
列表對(duì)象可調(diào)用? False
元組對(duì)象可調(diào)用? False
字典對(duì)象可調(diào)用? False
stu is callable? False
從上面的例子中可以得出:數(shù)值變量、列表對(duì)象、元組對(duì)象、字典對(duì)象等是不可調(diào)用的,這顯而易見,且這種調(diào)用也沒有實(shí)際意義的;類中未實(shí)現(xiàn)__call__()方法,類的實(shí)例也是不能調(diào)用的。
callable()方法主要在程序中調(diào)用某個(gè)對(duì)象時(shí)而預(yù)防出錯(cuò)設(shè)置的函數(shù)。用戶在調(diào)用某個(gè)對(duì)象前,預(yù)先使用callable()方法判斷其可調(diào)用性而避免出現(xiàn)TypeError錯(cuò)誤。
新聞熱點(diǎn)
疑難解答
圖片精選