Get the object name of a specific object from namedtuple

前端 未结 2 480
迷失自我
迷失自我 2021-01-24 03:28

I have recently discovered namedtuple and want to use it to replace my icky large class definitions but I am curious if there is a smart way to retrieve the object\

2条回答
  •  鱼传尺愫
    2021-01-24 04:03

    A namedtuple instance has a namedtuple._asdict() method that returns an ordered dictionary:

    >>> from collections import namedtuple
    >>> MyStruct = namedtuple("MyStruct", "Var1 Var2 Var3")
    >>> value = MyStruct('foo', 'bar', 'baz')
    >>> value._asdict()
    OrderedDict([('Var1', 'foo'), ('Var2', 'bar'), ('Var3', 'baz')])
    

    This gives you an ordered dictionary with keys and values corresponding to the contents.

    However, it is not clear to me what you are trying to achieve; what exactly is wrong with just selecting the right field directly?

    print 'Var1: {}'.format(value.Var1)
    

    or picking out specific fields with str.format():

    print 'Var1: {0.Var1}, Var3: {0.Var3}'.format(value)
    

提交回复
热议问题