標籤:ati att ocs 進階 錯誤 ISE link mod cep
官網解釋:
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__