具名元组

作者: Python高效编程 | 来源:发表于2019-01-18 22:02 被阅读4次

    具名元组(namedtuple) 是 python 标准库 collections 中的工厂函数。它接受两个参数,第一个参数表示类的名称,第二个参数是类的字段名。后者可以是可迭代对象,也可以是空格隔开的字符串。然后,我们通过一串参数的形式将参数传递到构造函数中。这样,我们既可以通过字段名访问元素,也可以用索引访问元素。

    from collections import namedtuple
    ToDo = namedtuple('ToDo', 'date content priority')
    t = ToDo(12, 'null', 1)
    print(t.date)
    print(t[1])
    # output:
    # 12
    # null
    

    下面是具名元组的演示程序:
    我们创建了一个 ToDoList 类,并且支持 + 、索引、切片与显示等操作。并且通过格式化输出,美化打印结果。

    from collections import namedtuple
    
    ToDo = namedtuple('ToDo', 'date content priority')
    
    
    class ToDoList:
        def __init__(self):
            self.item = []
    
        def add(self, date, content, priority):
            self.item.append(ToDo(date, content, priority))
    
        def _modify(self, item):
            self.item = item
    
        @property
        def _getitem(self):
            return self.item
    
        def __getitem__(self, pos):
            return self.item[pos]
    
        def __add__(self, other):
            item = self._getitem + other._getitem
            t = ToDoList()
            t._modify(item)
            return t
    
        def __repr__(self):
            items = self._getitem
            text = '{:<5}{:^10}{:^10}'.format('date', 'content', 'priority')
            fmt = '{:<5}{:^10}{:^10}'
            for item in items:
                text += '\n'
                text += fmt.format(item.date, item.content, item.priority)
    
            return text
    
        __str__ = __repr__
    
    
    def main():
        t1 = ToDoList()
        t1.add(12, 'play', 0)
        t1.add(8, 'seek', 6)
        t2 = ToDoList()
        t2.add(4, 'sleep', 2)
        t3 = t1 + t2
        print(t3)
    
    
    
    if __name__ == '__main__':
        main()
    # 输出
    # date  content   priority 
    #12      play       0     
    #8       seek       6     
    # 4      sleep       2   
    

    相关文章

      网友评论

        本文标题:具名元组

        本文链接:https://www.haomeiwen.com/subject/lfpodqtx.html