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
相关推荐
AI蜗牛之家1 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
C++ 老炮儿的技术栈1 小时前
UDP 与 TCP 的区别是什么?
开发语言·c++·windows·算法·visual studio
wgslucky1 小时前
Dubbo报错:module java.base does not “opens java.lang“ to unnamed module
java·开发语言·dubbo
whyeekkk1 小时前
python打卡第48天
开发语言·python
DougLiang2 小时前
关于easyexcel动态下拉选问题处理
java·开发语言
全职计算机毕业设计3 小时前
基于Java Web的校园失物招领平台设计与实现
java·开发语言·前端
5:003 小时前
云备份项目
linux·开发语言·c++
Eiceblue4 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550404 小时前
初级程序员入门指南
javascript·python·算法
笨笨马甲4 小时前
Qt Quick模块功能及架构
开发语言·qt