標籤:直接 end log [] __init__ object append pytho 函數
__call__在Python中,函數其實是一個對象:>>> f = abs>>> f.__name__‘abs‘>>> f(-123)由於 f 可以被調用,所以,f 被稱為可調用對象。所有的函數都是可調用對象。一個類執行個體也可以變成一個可調用對象,只需要實現一個特殊方法__call__()。我們把 Person 類變成一個可調用對象:class Person(object): def __init__(self, name, gender): self.name = name self.gender = gender def __call__(self, friend): print ‘My name is %s...‘ % self.name print ‘My friend is %s...‘ % friend現在可以對 Person 執行個體直接調用:>>> p = Person(‘Bob‘, ‘male‘)>>> p(‘Tim‘)My name is Bob...My friend is Tim...單看 p(‘Tim‘) 你無法確定 p 是一個函數還是一個類執行個體,所以,在Python中,函數也是對象,對象和函數的區別並不顯著。任務改進一下前面定義的斐波那契數列:class Fib(object): ???請加一個__call__方法,讓調用更簡單:>>> f = Fib()>>> print f(10)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
可以把執行個體對象用類似函數的形式表示,進一步模糊了函數和對象之間的概念
class Fib(object): def __init__(self): pass def __call__(self,num): a,b = 0,1; self.l=[] for i in range (num): self.l.append(a) a,b= b,a+b return self.l def __str__(self): return str(self.l) __rept__=__str__ f = Fib()print f(10)
python中的__call__的特殊函數(轉載)