[Python-ideas] namedtuple() subclasses again
Antoine Pitrou
solipsis at pitrou.net
Sun Mar 27 17:59:55 CEST 2011
On Fri, 25 Mar 2011 15:06:37 +0100
Jan Kaliszewski <zuo at chopin.edu.pl> wrote:
>
> ...and especially:
>
> class MyAbstractNamedTuple(namedtuple.abc):
> def __repr__(self):
> "My sophisticated __repr__()"
> # and e.g. some new methods...
>
> class MyNamedTupleA(MyAbstractNamedTuple):
> _fields = 'a b c'
>
> class MyNamedTupleB(MyAbstractNamedTuple):
> _fields = (
> 'one_field',
> 'another_field',
> 'and_another_one',
> )
Can't you multiple inheritance instead?
>>> class Base(tuple):
... def _method(self): return 5
... __slots__ = ()
...
>>> class C(Base, namedtuple('Point', 'x y')):
... __slots__ = ()
...
>>> c = C(x=1, y=2)
>>> c
C(x=1, y=2)
>>> c._method()
5
>>> c.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute '__dict__'
>>> a, b = c
>>> a
1
>>> b
2
Antoine.
More information about the Python-ideas
mailing list