【问题标题】:Can Python's Bunch be used recursively?Python的Bunch可以递归使用吗?
【发布时间】:2016-05-31 00:38:00
【问题描述】:

使用bunch,可以递归使用Bunch吗?

例如:

from bunch import Bunch
b = Bunch({'hello': {'world': 'foo'}})
b.hello
>>> {'world': 'foo'}

所以,很明显:

b.hello.world
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-effaad77643b> in <module>()
----> 1 b.hello.world

AttributeError: 'dict' object has no attribute 'world'

我知道我能做到……

b = Bunch({'hello': Bunch({'world': 'foo'})})

...但这太糟糕了。

【问题讨论】:

    标签: python bunch


    【解决方案1】:

    挖掘源代码,这可以通过fromDict 方法完成。

    b = Bunch.fromDict({'hello': {'world': 'foo'}})
    b.hello.world
    >>> 'foo'
    

    【讨论】:

      【解决方案2】:

      Bunch.fromDict 可以为您施展魔法:

      >>> d = {'hello': {'world': 'foo'}}
      >>> b = Bunch.fromDict(d)
      >>> b
      Bunch(hello=Bunch(world='foo'))
      >>> b.hello
      Bunch(world='foo')
      >>> b.hello.world
      'foo'
      

      【讨论】:

        猜你喜欢
        • 2019-04-18
        • 1970-01-01
        • 1970-01-01
        • 2011-12-28
        • 2022-06-25
        • 1970-01-01
        • 2016-11-10
        • 2011-09-13
        • 1970-01-01
        相关资源
        最近更新 更多