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
相关推荐
coding随想13 分钟前
掌控网页的魔法之书:JavaScript DOM的奇幻之旅
开发语言·javascript·ecmascript
Norvyn_722 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
爱吃烤鸡翅的酸菜鱼32 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
chao_78939 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥1 小时前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
都叫我大帅哥3 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`5 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j