工作中的代码,功能不错。
class Storage(dict):
"""A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`.
>>> o = storage(a=1)
>>> o.a
1
>>> o['a']
1
>>> o.a = 2
>>> o['a']
2
>>> del o.a
>>> o.a
Traceback (most recent call last):
...
AttributeError: 'a'
"""
def __getattr__(self, key):
try:
return self[key]
except KeyError, k:
raise AttributeError, k
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError, k:
raise AttributeError, k
def __repr__(self):
return '<Storage ' + dict.__repr__(self) + '>'
本文介绍了一个名为Storage的类,它提供了一种类似于字典的对象,允许通过键名和键路径来访问和设置属性,同时支持键的动态添加、删除和属性访问。
12万+

被折叠的 条评论
为什么被折叠?



