[Python-ideas] namedtuple() subclasses again

Jan Kaliszewski zuo at chopin.edu.pl
Sun Mar 27 22:53:16 CEST 2011


Antoine Pitrou dixit (2011-03-27, 17:59):

> 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

You're right. But my idea was to make it simple and clean from the user
point of view (without all those __slots__ etc.).

Another approach could be a decorator transforming a given class into
namedtuple with methods defined in that class:

    @namedtuple.from_class
    class MyRecord:  # or e.g. class MyRecord(MyMixinWithSomeMethods):
        fields = 'username password'
        def __str__(self):
            return '{0.__class__}({0.username}, ...)'.format(self)

Regards.
*j




More information about the Python-ideas mailing list