python getattribute方法
python getattribute方法
__getattr__回顾:
class Foo:
def __init__(self, x):
self.x = x
def __getattr__(self, item):
print( 执行的是我 )
# return self.__dict__[item]
f1 = Foo(10)
print(f1.x) # 10
f1.xxxxxx # 不存在的属性访问,触发__getattr__
__getattribute__
class Foo:
def __init__(self, x):
self.x = x
def __getattribute__(self, item):
print( 不管是否存在,我都会执行 )
f1 = Foo(10)
f1.x
f1.xxxxxx
raise AttributeError()
class Foo:
def __init__(self, x):
self.x = x
def __getattr__(self, item):
print( 执行的是我 )
# return self.__dict__[item]
def __getattribute__(self, item):
print( 不管是否存在,我都会执行 )
raise AttributeError( 哈哈 )
f1 = Foo(10) # 不管是否存在,我都会执行
f1.x # 执行的是我
f1.xxxxxx # 不管是否存在,我都会执行 → 执行的是我
# 当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,
# 除非__getattribute__在执行过程中抛出异常AttributeError
再次注意:当__getattribute__()与__getattr__()同时存在,只会执行__getattrbute__(),除非__getattribute__()在执行过程中抛出异常AttributeError
其实相当于__getattribute__()是__getattr__()的老大,当__getattribute__()方法抛出异常AttributeError()时,自动调用__getattr()__。
__getattr()__只接受AttributeError()的错误信息才运行。其他错误信息一律不接受。
__getattr()__只接受AttributeError()的错误信息代码示例:
class Foo:
def __init__(self, x):
self.x = x
def __getattr__(self, item):
print( 执行的是我 )
# return self.__dict__[item]
def __getattribute__(self, item):
print( 不管是否存在,我都会执行 )
raise TabError( 哈哈 )
f1 = Foo(10)
f1.x
f1.xxxxxx
__getattr()__只接受AttributeError()的错误信息运行结果:
不管是否存在,我都会执行
Traceback (most recent call last):
File H:/Flask/shiyanlou/laonanhai/__getattribute__.py, line 4, in
f1.x
File H:/Flask/shiyanlou/laonanhai/__getattribute__.py, line 9, in __getattribute__
raise TabError( 哈哈 )
TabError: 哈哈
#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格
下一篇:手机闪存速度排行
推荐阅读
留言与评论(共有 14 条评论) |
本站网友 连接池 | 28分钟前 发表 |
print( 执行的是我 ) # return self.__dict__[item] f1 = Foo(10) print(f1.x) # 10 f1.xxxxxx # 不存在的属性访问,触发__getattr__ __getattribute__ class Foo | |
本站网友 超燃冲压发动机 | 28分钟前 发表 |
item) | |
本站网友 哈尔滨西餐 | 19分钟前 发表 |
self.x = x def __getattr__(self | |
本站网友 100亿日元 | 14分钟前 发表 |
class Foo | |
本站网友 温泉二手房 | 10分钟前 发表 |
print( 不管是否存在 | |
本站网友 岭南新世界锦云峰 | 6分钟前 发表 |
print( 执行的是我 ) # return self.__dict__[item] def __getattribute__(self | |
本站网友 氨茶碱注射液说明书 | 20分钟前 发表 |
print( 不管是否存在 | |
本站网友 华夏邓白氏 | 14分钟前 发表 |
我都会执行 ) raise TabError( 哈哈 ) f1 = Foo(10) f1.x f1.xxxxxx __getattr()__只接受AttributeError()的错误信息运行结果 | |
本站网友 深圳君汇新天 | 30分钟前 发表 |
我都会执行 f1.x # 执行的是我 f1.xxxxxx # 不管是否存在 | |
本站网友 上海酒吧网 | 2分钟前 发表 |
x) | |
本站网友 浙江电力 | 23分钟前 发表 |
我都会执行 ) raise TabError( 哈哈 ) f1 = Foo(10) f1.x f1.xxxxxx __getattr()__只接受AttributeError()的错误信息运行结果 | |
本站网友 迅达电梯公司 | 28分钟前 发表 |
python getattribute方法 __getattr__回顾 | |
本站网友 和悦论坛 | 11分钟前 发表 |
in f1.x File H |