求大神看下这个python 类的使用模式有什么问题,大神python,class Bunch(


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

求各位大神解释一下这个模式!谢谢了

Bunch Pattern 字面意思大概是指链式的束式结构.主要用于松散的数据存储数据。具体看例子

class Bunch(dict):    def __init__(self, *args, **kwargs):        super(Bunch, self).__init__(*args, **kwargs)        self.__dict__ = selfprint struct print struct.typeprint struct.sizeprint struct.genus.level# 输出{'type': 'flat', 'genus': {'intensity': 'hot', 'level': 'medium'}, 'BOOL': True, 'family': 'chordata', 'size': 'huge'}flathugemedium

如果是单纯的字典呢?

class Bunch(dict):    def __init__(self, *args, **kwargs):        super(Bunch, self).__init__(*args, **kwargs)        # self.__dict__ = self        pass# 输出{'type': 'flat', 'genus': {'intensity': 'hot', 'level': 'medium'}, 'BOOL': True, 'family': 'chordata', 'size': 'huge'}AttributeError: 'Bunch' object has no attribute 'type'

这里的用法,主要是能够扩展成为一个链式的结构持续的保存数据,尤其是 struct是一个Bunch的实例,而 struct.genus 又是一个 Bunch 实例。

用这个可是简洁的写出字典模拟的二叉树。大概如此吧。

编橙之家文章,

评论关闭