What are “named tuples” in Python?

前端 未结 11 2209
名媛妹妹
名媛妹妹 2020-11-22 06:58

Reading the changes in Python 3.1, I found something... unexpected:

The sys.version_info tuple is now a named tuple:

11条回答
  •  故里飘歌
    2020-11-22 07:22

    Everyone else has already answered it, but I think I still have something else to add.

    Namedtuple could be intuitively deemed as a shortcut to define a class.

    See a cumbersome and conventional way to define a class .

    class Duck:
        def __init__(self, color, weight):
            self.color = color
            self.weight = weight
    red_duck = Duck('red', '10')
    
        In [50]: red_duck
        Out[50]: <__main__.Duck at 0x1068e4e10>
        In [51]: red_duck.color
        Out[51]: 'red'
    

    As for namedtuple

    from collections import namedtuple
    Duck = namedtuple('Duck', ['color', 'weight'])
    red_duck = Duck('red', '10')
    
    In [54]: red_duck
    Out[54]: Duck(color='red', weight='10')
    In [55]: red_duck.color
    Out[55]: 'red'
    

提交回复
热议问题