How to use namedtuples in multiple inheritance

前端 未结 3 1255
花落未央
花落未央 2020-12-20 02:17

Is it possible to create a class that inherits from multiple instances of namedtuple, or create something to the same effect (having an immutable type that combines the fiel

3条回答
  •  一个人的身影
    2020-12-20 03:08

    This code adopts a similar approach to Francis Colas', although it's somewhat longer :)

    It's a factory function that takes any number of parent namedtuples, and creates a new namedtuple that has all the fields in the parents, in order, skipping any duplicate field names.

    from collections import namedtuple
    
    def combined_namedtuple(typename, *parents):
        #Gather fields, in order, from parents, skipping dupes
        fields = []
        for t in parents:
            for f in t._fields:
                if f not in fields:
                    fields.append(f)
        return namedtuple(typename, fields)
    
    nt1 = namedtuple('One', ['foo', 'qux'])
    nt2 = namedtuple('Two', ['bar', 'baz'])    
    
    Combo = combined_namedtuple('Combo', nt1, nt2)    
    ct = Combo(1, 2, 3, 4)
    print ct
    

    output

    Combo(foo=1, qux=2, bar=3, baz=4)
    

提交回复
热议问题