python中的__call__的特殊函數(轉載)

來源:互聯網
上載者:User

標籤:直接   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__的特殊函數(轉載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.