首页 > 其他 > 详细

向字典 a_dict=dict(a=2,b=3)添加 a_dict.a # 2属性

时间:2019-08-14 16:42:21      阅读:139      评论:0      收藏:0      [点我收藏+]
class Struct(dict):
"""
Object-Dict
>>> o = Struct({‘a‘:1})
>>> o.a
>>> 1
>>> o.b
>>> None
"""
def __init__(self, *e, **f):
if e:
self.update(e[0])
if f:
self.update(f)

def __getattr__(self, name):
# Pickle is trying to get state from your object, and dict doesn‘t implement it.
# Your __getattr__ is being called with "__getstate__" to find that magic method,
# and returning None instead of raising AttributeError as it should.
if name.startswith(‘__‘):
raise AttributeError
return self.get(name)

def __setattr__(self, name, val):
self[name] = val

def __delattr__(self, name):
self.pop(name, None)

def __hash__(self):
return id(self)

def copy(self):
return Struct(dict.copy(self))

a_dict=dict(a=2, b=3)
a_dict=Struct(a_dict)
b_dict=Struct(a=2, b=3)
print(a_dict.a) # 2
print(b_dict.a) # 2

向字典 a_dict=dict(a=2,b=3)添加 a_dict.a # 2属性

原文:https://www.cnblogs.com/laowang-106/p/11352846.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!