Python的__getattr__方法學習


內容部分來自網絡

__getattr__函數的作用: 如果屬性查找(attribute lookup)在實例以及對應的類中(通過__dict__)失敗, 那么會調用到類的__getattr__函數;

如果沒有定義這個函數,那么拋出AttributeError異常。由此可見,__getattr__一定是作用於屬性查找的最后一步

舉個栗子:

 1 class A(object):
 2     def __init__(self, a, b):
 3         self.a1 = a
 4         self.b1 = b
 5         print('init')
 6 
 7     def mydefault(self, *args):
 8         print('default:' + str(args[0]))
 9 
10     def __getattr__(self, name):
11         print("other fn:", name)
12         return self.mydefault
13 
14 
15 a1 = A(10, 20)
16 a1.fn1(33)
17 a1.fn2('hello')

運行結果:

init
other fn: fn1
default:33
other fn: fn2
default:hello

第16行調用fn1屬性時,查找不到次屬性,程序調用__getattr__方法

用__getattr__方法可以處理調用屬性異常

class Student(object):
    def __getattr__(self, attrname):
        if attrname == "age":
            return 'age:40'
        else:
            raise AttributeError(attrname)

x = Student()
print(x.age)  # 40
print(x.name)

這里定義一個Student類和實例x,並沒有屬性age,當執行x.age,就調用_getattr_方法動態創建一個屬性,執行x.name時,__getattr__方法沒有對其處理,拋出異常

age:40
  File "XXXX.py", line 10, in <module>
    print(x.name)
  File "XXXX.py", line 6, in __getattr__
    raise AttributeError(attrname)
AttributeError: name

下面展示一個_getattr_經典應用的例子,可以調用dict的鍵值對

class ObjectDict(dict):
    def __init__(self, *args, **kwargs):
        super(ObjectDict, self).__init__(*args, **kwargs)

    def __getattr__(self, name):
        value = self[name]
        if isinstance(value, dict):
            value = ObjectDict(value)
        return value


if __name__ == '__main__':
    od = ObjectDict(asf = {'a': 1}, d = True)
    print(od.asf, od.asf.a)  # {'a': 1} 1
    print(od.d)  # True

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM