__call__():Python中,只要在創建類型的時候定義了__call__()方法,這個類型就是可調用的。
Python中的所有東西都是對象,其中包括Int/str/func/class這四類,它們都是對象,都是從一個類創建而來的。元類就是創建這些對象的東西,type就是Python的內建元類。
其中,func是可調用的對象,說明在創建它的類型(父類或它本身)的時候,定義了__call__()方法。
>>>callable(lambda:8)
True
>>>def fn():
pass
>>>callable(fn)
True
所以一個類實例也可以成為類似函數這樣能直接調用的對象,只要定義的時候有__call__()方法就可以。
>>>class Reader():
def __init__(self,name,nationality):
self.name = name
self.nationality = nationality
def __call__(self):
print('Reader: %s Nationality: %s' % (self.name, self.nationality))
>>>r = Reader('Annie','Chinese')
>>>r()
Reader:Annie Nationality: Chinese
__call__()方法還可以帶參數
定義一個可以直接調用類實例的Reader類,並可統計讀者數量
>>>class Reader():
count = 0
def __init__(self,name,nationality):
self.name = name
self.nationality = nationality
Reader.count += 1
def __call__(self, behave):
print('Reader: %s' % self.name)
print('Nationality: %s' % self.nationality)
print('%s is being %s.' % (self.name, behave))
print('The total number of readers is %s.' % Reader.count)
>>>a = Reader('Annie','Chinese')
>>>a('Nice')
Reader: Annie
Nationality: Chinese
Annie is being Nice.
The total number of readers is 1.
>>>b = Reader('Adam','American')
>>>b('Silly')
Reader: Adam
Nationality: American
Adam is being Silly.
The total number of readers is 2. #自動增加