Python: Extending a predefined named tuple

后端 未结 3 2003
-上瘾入骨i
-上瘾入骨i 2020-12-14 17:06

I have the following named tuple:

from collections import namedtuple
ReadElement = namedtuple(\'ReadElement\', \'address value\')

and then

3条回答
  •  天命终不由人
    2020-12-14 17:31

    Extending Martijn Pieters' answer: there is a way to make the new namedtuple class a subclass of the other, without having to hack. Simply create the new namedtuple separately, and then use its __new__ method instead of using super:

    from collections import namedtuple
    
    class ReadElement(namedtuple('ReadElement', ('address', 'value'))):
        def compute(self):
            return self.value + 1
    
    _LookupElement = namedtuple('_LookupElement', ReadElement._fields + ('lookups',))
    
    class LookupElement(_LookupElement, ReadElement):
        def __new__(self, address, value, lookups):
            return _LookupElement.__new__(LookupElement, address, value, lookups)
    
    assert issubclass(LookupElement, ReadElement)
    l = LookupElement('ad', 1, dict())
    assert isinstance(l, ReadElement)
    assert l.compute() == 2
    

    It seems that this also works without even overriding __new__ !

    from collections import namedtuple
    
    class ReadElement(namedtuple('ReadElement', ('address', 'value'))):
        def compute(self):
            return self.value + 1
    
    class LookupElement(namedtuple('LookupElement', ReadElement._fields + ('lookups',)),
                        ReadElement):
        """nothing special to do"""
        pass
    

提交回复
热议问题