首页 >> 要闻 > 资讯 >
python getattribute、get、getattr、getitem等用法
__getattribute__
__getattribute__是属性访问拦截器,就是当类的属性被访问时,会自动调用类的__getattribute__方法。
参考代码:
class Attribute(object): def __init__(self): self.name = '247gzs' self.age = 24 self.sex = '男' def __getattribute__(self, item): print("__getattribute__() is called", item) return object.__getattribute__(self, item)if __name__ == '__main__': attribute = Attribute() print(attribute.name) # output__getattribute__() is called name247gzs代码执行过程中,当调用实例对象attribute的name属性时,不会直接打印,而是把name的值作为实参传进__getattribute__方法中,经过一系列操作后,再把name的值返回。
python中只要定义了继承object的类,就默认存在属性拦截器,只不过是拦截后没有进行任何操作,而是直接返回。
我们可以自己改写__getattribute__方法来实现相关功能,比如查看权限、打印log日志等。
getattr、hasattr、setattr
对象属性的判断。
参考代码:
class Attribute(object): passif __name__ == '__main__': attribute = Attribute() print('-------- 未设置 --------') print(hasattr(attribute, 'name')) # 判断是否存在属性 print(hasattr(attribute, 'age')) setattr(attribute, 'name', '247gzs') # 设置属性值 setattr(attribute, 'age', 24) print('-------- 已设置 --------') print('-------- 判断是否存在 --------') print(hasattr(attribute, 'name')) print(hasattr(attribute, 'age')) print('-------- 获取属性值 --------') print(getattr(attribute, 'name')) # 获取属性值 print(getattr(attribute, 'age')) print(getattr(attribute, 'sex', '男')) # output-------- 未设置 --------FalseFalse-------- 已设置 ---------------- 判断是否存在 --------TrueTrue-------- 获取属性值 --------247gzs24男__getattr__、__setattr__、__delattr__
类支持.操作来访问属性;定制功能:耗时、日志等等。
参考代码:
class Attribute(object): """ 使类支持 . 操作,默认情况下,类支持 . 操作 """ def __getattr__(self, item): print("__getitem__() is called", item) if item in self.__dict__: return self.__dict__[item] def __setattr__(self, key, value): print("__setitem__() is called", key, value) self.__dict__[key] = value def __delattr__(self, item): print("__delitem__() is called", item) del self.__dict__[item]if __name__ == '__main__': attribute = Attribute() attribute.name = '247gzs' attribute.age = 24 print(attribute.name, attribute.age) del attribute.name # print(attribute['age']) # 报错,不支持此方法 # output__setitem__() is called name wxs__setitem__() is called age 24247gzs 24__delitem__() is called name__getitem__、__setitem__、__delitem__
类支持通过[]来访问属性
参考代码:
class Attribute(object): """ 给类添加 [] 操作 """ def __getitem__(self, item): print("__getitem__() is called", item) if item in self.__dict__: return self.__dict__[item] def __setitem__(self, key, value): print("__setitem__() is called", key, value) self.__dict__[key] = value def __delitem__(self, key): print("__delitem__() is called", key) del self.__dict__[key]if __name__ == '__main__': attribute = Attribute() attribute['name'] = '247gzs' print(attribute['name']) del attribute['name'] # output__setitem__() is called name wxs__getitem__() is called name247gzs__delitem__() is called name__get__、__set__、__delete__
参考代码:
# 定义描述符class Attribute(object): def __init__(self, key, value_type): """ :param key: 用来操作底层属性字典 :param value_type: 用来表示期望的数据类型 """ self.key = key self.value_type = value_type def __get__(self, instance, owner): print('执行了__get__') return instance.__dict__[self.key] # return p2.name def __set__(self, instance, value): print('执行了__set__', self) if not isinstance(value, self.value_type): # 用来判断用户传入的是否符合要求 raise TypeError('%s 传入的不是 %s' % (self.key, self.value_type)) # 抛出类型异常,提示用户程序终止 instance.__dict__[self.key] = value # 符合要求,则设置属性对应的值 def __delete__(self, instance): print('执行了__delete__') instance.__dict__.pop(self.key)# 定义一个人的类(被代理的类)class People(object): name = Attribute('name', str) # 用描述符代理了name这个属性,相当于执行了Attribute中的self.__set__ age = Attribute('age', int) salary = Attribute('salary', float) def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salaryperson = People('Wxs', 24, 11.2)# 访问print(person.name)# 赋值person.name = '247gzs'person.age = 25# output执行了__set__ 执行了__set__ 执行了__set__ 执行了__get__247gzs执行了__set__ 执行了__set__参考文档:
[1] https://blog.csdn.net/yiifaa/article/details/78068962[2] https://www.cnblogs.com/flashBoxer/p/9771797.html[3] https://www.cnblogs.com/andy1031/p/10923834.html[4] http://blog.itpub.net/26736162/viewspace-2643143/[5] https://blog.csdn.net/yitiaodashu/article/details/78974596 (__getattribute__)[6] https://www.cnblogs.com/Meanwey/p/9898222.html (__get__、__set__、__delete__)[7] https://www.v2ex.com/t/511140[8] https://blog.csdn.net/yiifaa/article/details/78068962免责声明:本文由用户上传,与本网站立场无关。财经信息仅供读者参考,并不构成投资建议。投资者据此操作,风险自担。 如有侵权请联系删除!
分享:
相关阅读
最新文章
-
大众CC作为一款备受关注的中型轿车,凭借其优雅的设计和出色的性能一直吸引着众多消费者的目光。2025款大众CC...浏览全文>>
-
2025款阜阳途锐新车正式上市,凭借其卓越的性能和豪华配置吸引了众多消费者的关注。这款车型以最低售价55 88...浏览全文>>
-
在准备购买一辆汽车之前,了解车辆的落地价格是非常重要的。所谓落地价,是指购车时除了车款之外还需要支付的...浏览全文>>
-
安徽淮南地区的长安启源E07作为一款备受关注的新能源车型,凭借其时尚的设计、丰富的配置以及出色的续航能力,...浏览全文>>
-
安徽淮南长安启源A05 2025款新车现已正式上市,这款车型以其高性价比和出色性能吸引了众多消费者的关注。作为...浏览全文>>
-
安徽阜阳地区的威然车型在近期进行了配置上的升级,对于想要购买这款MPV的消费者来说,这是一个值得关注的消息...浏览全文>>
-
随着汽车市场的不断发展,SUV车型因其宽敞的空间和多功能性受到了越来越多消费者的青睐。作为大众旗下的高端旗...浏览全文>>
-
安徽蚌埠地区想要购买长安启源E07这款新能源汽车的朋友,可以参考以下信息来做出更明智的选择。长安启源E07定...浏览全文>>
-
随着汽车市场的不断发展,2025款安庆高尔夫作为一款备受关注的车型,其价格和配置自然成为消费者热议的话题。...浏览全文>>
-
近期,安徽蚌埠地区的帕萨特车型迎来了新一轮的价格调整,其落地价再次创下新低,吸引了众多消费者的关注。作...浏览全文>>
大家爱看
频道推荐
站长推荐
- 悉尼最后几个年薪低于 10 万美元的郊区
- 2025 年新南威尔士州值得投资的地方
- 揭秘在澳大利亚买房需要多少收入
- 悉尼最后几个年薪低于 10 万美元的郊区
- 昆士兰有望成为澳大利亚房地产强国之一
- MSI 推出首款双模式 4K 曲面电竞显示器
- 飞利浦 Screeneo GamePix 900:在发布前进行预览
- 您会在这个奇怪的电动露营三轮车里露营吗
- Meross 推出支持 Matter 的智能恒温器
- 配备出色 3K OLED 显示屏的 Acer Swift 16 现已降价至史上最低价
- Acer Predator Helios 18 RTX 4080 游戏笔记本电脑 现优惠 725 美元
- VivoX200Pro视频和新样张揭示了200MP蔡司变焦相机的锐利眼睛可以达到多远
- 派对氛围天文爱好者又一次欣赏到极光秀
- iPhone16相机控制按钮有史以来最不苹果的东西
- 贾雷尔夸萨与利物浦签订新合同
- 首款在安兔兔上得分300万的手机拥有非常强大的SoC即将发布
- HumaninMotionRobotics的自平衡XoMotion外骨骼获得加拿大批准用于物理治疗
- 龙宫样本对之前关于富碳小行星形成的观点提出了质疑
- 凯文德布劳内伤情更新曼城球星的伤势进展和可能的回归日期
- 实验室实验表明用核武器轰炸一颗巨大的小行星可以拯救地球