def Map(*args, **kwargs):
value = kwargs.get('_default', None)
if kwargs.has_key('_default'): del kwargs['_default']
# CONSIDER You may want to look at the collections.defaultdict class.
# It takes in a factory function for default values.
#
# You can also implement your class by overriding the __missing__ method
# of the dict class, rather than overriding the __getitem__.
#
# Both were added in Python 2.5 according to the documentation.
class _DefMap(dict):
'But CONSIDER http://pypi.python.org/pypi/bunch/1.0.0 '
def __init__(self, *a, **kw):
dict.__init__(self, *a, **kw)
self.__dict__ = self
def __getitem__(self, key):
if not self.has_key(key):
if hasattr(value, '__call__'):
self[key] = value(key)
else:
self[key] = copy.deepcopy(value)
return dict.__getitem__(self, key)
return _DefMap(*args, **kwargs)
你绝对有必要把它建立在口述的基础上吗?Python对象可以动态获取属性,只需很少的额外管道:
你在找
__getitem__
吗?在或者你在寻找相反的答案,通过
^{pr2}$__getattr__
?在(编辑:正如Paul McGuire在评论中所指出的那样,这段代码只展示了完整解决方案的基本原理。)
是的,如果你想把它当作一个项目列表,而不滥用
__dict__
。在下面是我以前对Mash问题的回答。它提供了一个默认值,默认值可能是一个方法或一个对象,如果它是一个对象,它将深度克隆(而不是只是热链接),如果它被多次使用。在
它将其简单键值公开为
.key
:相关问题 更多 >
编程相关推荐