动态属性能够用来描述变化的类,在实际应用中容易遇到用到。
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