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 分钟前
裸仓库 + Git Bash 搭建 本地 Git 服务端与客户端
开发语言·git·bash
智能砖头6 分钟前
LangChain 与 LlamaIndex 深度对比与选型指南
人工智能·python
G探险者21 分钟前
《如何在 Spring 中实现 MQ 消息的自动重连:监听与发送双通道策略》
java·开发语言·rpc
weixin_437398211 小时前
转Go学习笔记
linux·服务器·开发语言·后端·架构·golang
StrongerIrene1 小时前
rs build 的process.env的值undefined解决方案
开发语言·javascript·ecmascript
风逸hhh1 小时前
python打卡day58@浙大疏锦行
开发语言·python
让我们一起加油好吗2 小时前
【C++】list 简介与模拟实现(详解)
开发语言·c++·visualstudio·stl·list
Q_970956392 小时前
java+vue+SpringBoo足球社区管理系统(程序+数据库+报告+部署教程+答辩指导)
java·开发语言·数据库
为了更好的明天而战2 小时前
Java 中的 ArrayList 和 LinkedList 区别详解(源码级理解)
java·开发语言
烛阴2 小时前
一文搞懂 Python 闭包:让你的代码瞬间“高级”起来!
前端·python