zoukankan      html  css  js  c++  java
  • 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__ = 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.(不仅仅用于建树)

  • 相关阅读:
    6389. 【NOIP2019模拟2019.10.26】小w学图论
    6383. 【NOIP2019模拟2019.10.07】果实摘取
    三分查找求极值
    51Nod 1278 相离的圆
    51 Nod 1092 回文字符串
    关于原根(来自百度百科)
    Hdu 1358 Period
    最大子矩阵和
    51 Nod 1072 威佐夫游戏
    The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online(2018 青岛网络预选赛)
  • 原文地址:https://www.cnblogs.com/pannyvan/p/4445416.html
Copyright © 2011-2022 走看看