python类动态属性,以属性方式访问字典

动态属性能够用来描述变化的类,在实际应用中容易遇到用到。

python 复制代码
import logging
class Sample:
    def __init__(self):
        self.time=None
        self.sampleid=None
        self.mass=None
        self.beizhu=""
        self.num=0
        self.items={}#字典属性
    def __getattribute__(self, attr): #注意:attr是传入的属性名,不是属性值
        # print(attr)
        if attr!="items":   
            v=self.items.get(attr)
            if v!=None:
                return  v
        return object.__getattribute__(self, attr) #返回属性
    def __setattr__(self, attr,value): #注意:attr是传入的属性名,不是属性值
        # print([attr,value])
        # print(attr)
        # print(dir(self))
        if attr!="items": 
            # print(dir(self))
            if hasattr(self, "items") and self.items.get(attr)!=None:
                self.items[attr]=value
            else:
                return object.__setattr__(self, attr,value)    
        else:
            return object.__setattr__(self, attr,value)
    
if __name__=="__main__":
    s=Sample()
    s.sampleid="001"
    s.items={"a":"a","b":"b"}
    print(s.sampleid,s.a,s.b)
    s.a="a2"
    print(s.sampleid,s.a,s.b)

运行演示:

bash 复制代码
D:\ma\python\report__stand2\simple>python s1.py
001 a b
001 a2 b
相关推荐
越甲八千2 分钟前
uvicorn是啥
python
Dxy123931021611 分钟前
Python字符串处理全攻略
开发语言·python
毕设源码-朱学姐31 分钟前
【开题答辩全过程】以 基于Java的失物招领系统设计与实现为例,包含答辩的问题和答案
java·开发语言
Gomiko34 分钟前
JavaScript进阶(四):DOM监听
开发语言·javascript·ecmascript
清晓粼溪36 分钟前
统一异常处理
java·开发语言
Fiona-Dong39 分钟前
Louvain 算法
python·算法
坐吃山猪1 小时前
BrowserUse14-源码-ScreenShot模块-整理
linux·数据库·python
syt_10131 小时前
grid布局之-子项放置4
开发语言·javascript·ecmascript
喵了meme1 小时前
C语言实战2
c语言·开发语言·网络
charlie1145141911 小时前
现代C++工程实践:简单的IniParser3——改进我们的split
开发语言·c++·笔记·学习