Python 之 Bunch Pattern

When prototyping (or even finalizing) data structures such as trees, it can be useful to have a flexible class that will allow you to specify arbitrary attributes in the constructor. In these cases, the 「Bunch」 pattern (named by Alex Martelli in the Python Cookbook) can come in handy. There are many ways of implementing it, but the gist of it is the following:(實現數據結構,好比說樹的時候使用,有多種實現方式,要點以下)數據結構

class Bunch(dict):
    def __init__(self, *args, **kwds):
        super(Bunch, self).__init__(*args, **kwds)
        self.__dict__ = selfflex

There are several useful aspects to this pattern. First, it lets you create and set arbitrary ttributes by supplying them as command-line arguments:(這個pattern頗有用,第一,你可一設置任意的屬性)ui

>>> x = Bunch(name="Jayne Cobb", position="Public Relations")
>>> x.name
'Jayne Cobb'this

Second, by subclassing dict, you get lots of functionality for free, such as iterating over the keys/attributes or easily checking whether an attribute is present. Here’s an example:(第二,經過子類化的dict,你能夠得到不少功能,好比迭代的key-value,或者檢查屬性值是否存在等)ci

>>> T = Bunch
>>> t = T(left=T(left="a", right="b"), right=T(left="c"))
>>> t.left
{'right': 'b', 'left': 'a'}
>>> t.left.right
'b'
>>> t['left']['right']
'b'
>>> "left" in t.right
True
>>> "right" in t.right
Falseget

This pattern isn’t useful only when building trees, of course. You could use it for any situation where you’d want a flexible object whose attributes you could set in the constructor.(不單單用於建樹)it

相關文章
相關標籤/搜索