網(wǎng)站首頁 編程語言 正文
正文
__getattr__函數(shù)的作用: 如果屬性查找(attribute lookup)在實例以及對應的類中(通過__dict__)失敗, 那么會調(diào)用到類的__getattr__函數(shù);
如果沒有定義這個函數(shù),那么拋出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')
運行結(jié)果:
init
other fn: fn1
default:33
other fn: fn2
default:hello
第16行調(diào)用fn1屬性時,查找不到次屬性,程序調(diào)用__getattr__方法
用__getattr__方法可以處理調(diào)用屬性異常
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,當執(zhí)行x.age,就調(diào)用_getattr_方法動態(tài)創(chuàng)建一個屬性,執(zhí)行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_經(jīng)典應用的例子,可以調(diào)用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
相關(guān)推薦
- 2022-12-13 深入了解Go的HttpClient超時機制_Golang
- 2023-06-19 Docker?查詢、停止、刪除和重啟容器的詳細過程_docker
- 2021-11-23 Linux系統(tǒng)下SystemC環(huán)境配置方法_Linux
- 2021-12-06 linux下ceph分布式安裝使用教程_Linux
- 2022-12-04 C#目錄和文件管理操作詳解_C#教程
- 2023-07-09 前端axios請求,傳遞數(shù)組的時候會在url的后邊加中括號[]
- 2022-05-23 C#中的數(shù)據(jù)結(jié)構(gòu)介紹_C#教程
- 2022-10-01 C#?TreeView控件使用技巧匯總_C#教程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支