python Class:物件導向進階編程 __getattr__

來源:互聯網
上載者:User

標籤:ati   att   ocs   進階   錯誤   ISE   link   mod   cep   

官網解釋:

  • object.__getattr__(selfname)

  • Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.


當我們想調用Class中某些東西,而Class中沒有,解譯器鐵定報錯,停止運行,那有人就想了:真麻煩,每次都要重新執行一遍,如果當我調用錯了內容,程式能把我這個錯誤當預設程式執行,而不停止我程式運行就好了。so,為瞭解決這類問題,就出來了__getattr__這個函數了。

我猜的,因為解決程式困難也是一種需求。 


看沒有__getattr的出錯調用:

#!/usr/bin/python

# -*- coding: utf-8 -*-


class Student(object):

    def __init__(self):

        self.name = 'Michael'


s = Student()

print s.name

print s.score      #Class中沒有這個屬性

look, 第一個print正常執行,第二個由於Class中沒有這個屬性,所以就報錯了。


再看,帶__getattr__的Class:

#!/usr/bin/python

# -*- coding: utf-8 -*-


class Student(object):

    def __init__(self):

        self.name = 'Michael'


    def __getattr__(self, other):

        if other=='score':

            return 99

            

s = Student()

print s.name

print s.score   #Class中沒有這個屬性

print s.gg       #Class中沒有這個屬性


look again, print 的score 和 gg 在Class中都沒有定義,但都有輸出。因為程式往__getattr__中找,剛剛好定義了一個字元判斷 if other=='score':, 所以輸出了99 ,而gg一個字都沒提,就預設輸出None了。是不是感覺以後碼程式的時候再也不用擔心程式停止運行了。

python Class:物件導向進階編程 __getattr__

聯繫我們

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