日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python的getattr函數方法學習使用示例_python

作者:waws520 ? 更新時間: 2022-10-04 編程語言

正文

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

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

舉個栗子:

class A(object):
    def __init__(self, a, b):
        self.a1 = a
        self.b1 = b
        print('init')
    def mydefault(self, *args):
        print('default:' + str(args[0]))
    def __getattr__(self, name):
        print("other fn:", name)
        return self.mydefault
a1 = A(10, 20)
a1.fn1(33)
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

原文鏈接:https://juejin.cn/post/7119458309400166437

欄目分類
最近更新