1. 程式人生 > >python Class:面向對象高級編程 __getattr__

python Class:面向對象高級編程 __getattr__

perm att it is RoCE str list all clas name

官網解釋:

  • object.__getattr__(self, name)

  • 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__