“Bunch”设计模式:
首先,它能让我们以命令行参数的形式创建相关对象,并设置任何属性。
>>> class Bunch(dict):
def __init__(self,*args,**kwds):
super(Bunch,self).__init__(*args,**kwds)
self.__dict__=self
>>> x=Bunch(age="54",address="Beijing")
>>> x.age
'54'
由于它继承自dict类,我们可以自然而然获得大量相关内容,如对于相关键值/属性值的遍历,或者简单查询一个属性是否存在。
>>> T=Bunch
>>> t=T(left=T(left='a',right='b'),right=T(left='c'))
>>> t.left
{'left': 'a', 'right': 'b'}
>>> t.left.right
'b'
>>> t['left']['right']
'b'
>>> "left" in t.right
True
>>> "right"in t.right
False
摘自《Python算法教程》P34