Inheriting from a namedtuple base class
I think you can achieve what you want by including all of the fields
in the original named tuple, then adjusting the number of arguments
using __new__
as schwobaseggl suggests above. For instance, to address
max's case, where some of the input values are to be calculated
rather than supplied directly, the following works:
from collections import namedtuple
class A(namedtuple('A', 'a b c computed_value')):
def __new__(cls, a, b, c):
computed_value = (a + b + c)
return super(A, cls).__new__(cls, a, b, c, computed_value)
>>> A(1,2,3)
A(a=1, b=2, c=3, computed_value=6)
You can, but you have to override __new__
which is called implicitly before __init__
:
class Z(X):
def __new__(cls, a, b, c, d):
self = super(Z, cls).__new__(cls, a, b, c)
self.d = d
return self
>>> z = Z(1, 2, 3, 4)
>>> z
Z(a=1, b=2, c=3)
>>> z.d
4
But d
will be just an independent attribute!
>>> list(z)
[1, 2, 3]