Python中的Ruby Mash等价物?

2024-05-15 09:54:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在Ruby中,有一个很棒的库叫做Mash,它是一个散列,但是通过巧妙地使用missing_方法可以转换:

object['property']

^{pr2}$

这对mocks非常有用。有人知道Python中类似的事情吗?在


Tags: 方法objectproperty事情mocksrubymashmissing
3条回答

你绝对有必要把它建立在口述的基础上吗?Python对象可以动态获取属性,只需很少的额外管道:

>>> class C(object): pass
...
>>> z = C()
>>> z.blah = "xyzzy"
>>> dir(z)
['__class__', '__delattr__', '__dict__', ... '__weakref__', 'blah']

你在找__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"

或者你在寻找相反的答案,通过__getattr__?在

^{pr2}$

编辑:正如Paul McGuire在评论中所指出的那样,这段代码只展示了完整解决方案的基本原理。)

Is it absolutely necessary that you base this on a dict?

是的,如果你想把它当作一个项目列表,而不滥用__dict__。在

下面是我以前对Mash问题的回答。它提供了一个默认值,默认值可能是一个方法或一个对象,如果它是一个对象,它将深度克隆(而不是只是热链接),如果它被多次使用。在

它将其简单键值公开为.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)

相关问题 更多 >