網站首頁 編程語言 正文
正文
__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
相關推薦
- 2022-11-10 Android中PopupWindow彈出式窗口使用方法詳解_Android
- 2022-05-09 .Net?Core創建Api進行文件上傳功能_實用技巧
- 2022-07-24 .Net結構型設計模式之享元模式(Flyweight)_基礎應用
- 2022-07-14 React?Native采用Hermes熱更新打包方案詳解_React
- 2022-05-29 .NET中的字符串駐留池介紹_基礎應用
- 2023-01-07 Android?RecyclerBarChart繪制使用教程_Android
- 2022-12-22 React?Hook?-?自定義Hook的基本使用和案例講解_React
- 2021-12-05 C++11?關鍵字?const?使用小結_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支