Python 之 Bunch Pattern

來源:互聯網
上載者:User

標籤:

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__ = self

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很有用,第一,你可一設定任意的屬性)

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

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,或者檢查屬性值是否存在等)

>>> 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
False

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.(不僅僅用於建樹)

Python 之 Bunch Pattern

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.