Get the object name of a specific object from namedtuple

前端 未结 2 506
迷失自我
迷失自我 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:18

    namedtuplescan be indexed, so you don't need to turn one into a dict or use vars() to do what you want:

    MyStruct = namedtuple("MyStruct","Var1 Var2 Var3")
    instance = MyStruct(1, 2, 3)
    
    fields_to_print = {'Var1', 'Var2'}
    print(', '.join('{}: {}'.format(field, instance[i])
            for i, field in enumerate(instance._fields)
                if field in fields_to_print))
    

    Output:

    Var1: 1, Var2: 2
    

提交回复
热议问题