[英]Ruby Mash equivalent in Python?
in Ruby, there's this awesome library called a Mash which is a Hash but through clever use of missing_method can convert: 在Ruby中,有一个叫做Mash的真棒库,它是一个Hash但是通过巧妙地使用missing_method可以转换:
object['property']
to 至
object.property
This is really useful for mocks. 这对模拟非常有用。 Anyone know of a similar kind of thing in Python?
有人知道Python中有类似的东西吗?
Is it absolutely necessary that you base this on a dict? 你是否绝对有必要以dict为基础? Python objects can dynamically acquire attributes with very little extra plumbing:
Python对象可以通过非常少的额外管道动态获取属性:
>>> class C(object): pass
...
>>> z = C()
>>> z.blah = "xyzzy"
>>> dir(z)
['__class__', '__delattr__', '__dict__', ... '__weakref__', 'blah']
Is __getitem__
what you're looking for? __getitem__
你在寻找什么?
class C:
def __init__(self):
self.my_property = "Hello"
def __getitem__(self, name):
return getattr(self, name)
c = C()
print c['my_property'] # Prints "Hello"
or are you looking for the reverse of that, via __getattr__
? 或者你正在寻找相反的,通过
__getattr__
?
class D(dict):
def __getattr__(self, name):
return self[name]
d = D()
d['x'] = "Hello"
print d.x # Prints "Hello"
( Edit : As Paul McGuire kindly points out in the comments, this code only demonstrates the bare bones of a full solution.) ( 编辑 :正如Paul McGuire在评论中指出的那样,这段代码只展示了完整解决方案的基本原理。)
Is it absolutely necessary that you base this on a dict?
你是否绝对有必要以dict为基础?
Yes if you then want to treat it as a list of items, without abusing __dict__
. 是,如果您希望将其视为项目列表,而不是滥用
__dict__
。
The following is my old answer to the Mash question. 以下是我对Mash问题的旧回答。 It provides a default, the default may be a method or an object, if it's an object it will clone deeply ( not just hot-link) if it's used more than once.
它提供了一个默认,默认可能是一个方法或一个对象,如果它是一个对象时,它会深深地( 不只是热链接),如果它使用超过一次克隆。
And it exposes its simple key values as .key
: 它将其简单的键值公开为
.key
:
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)
Look here https://pypi.python.org/pypi/mash . 请看这里https://pypi.python.org/pypi/mash 。 Also you can convert dict to mash object.
您也可以将dict转换为mash对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.