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
相关推荐
shangan_310 分钟前
JAVA思维提升案例5
java·开发语言
孤芳剑影25 分钟前
F28335 的 EPWM 外设
开发语言·单片机·嵌入式硬件
乱打一通28 分钟前
C++里的随机数
开发语言·c++
2402_8575834929 分钟前
春意融融:Spring Boot技术在“衣依”服装销售平台的应用
java·开发语言·数据库
zty郑桐羽呀34 分钟前
[C++] 小游戏 征伐 SLG DNF 0.0.1 版本 zty出品
开发语言·数据结构·c++·算法·开源·zty郑桐羽呀·zty
zh路西法42 分钟前
【Matlab绘图】从Excel导入表格并进行三维绘图
开发语言·matlab·excel
2401_8582861144 分钟前
68.【C语言】动态内存管理(重点)(1)
c语言·开发语言·数据结构
奋斗的小鹰1 小时前
kotlin 委托
android·开发语言·kotlin
最近好楠啊1 小时前
Pytorch实现玉米基因表达量预测模型
人工智能·pytorch·python
卑微求AC1 小时前
(C语言贪吃蛇)14.用绝对值方式解决不合理的走位
linux·c语言·开发语言·嵌入式·c语言贪吃蛇