subclassing list and adding other variables ?

Peter Otten __peter__ at web.de
Thu Mar 11 18:00:49 EST 2004


GrelEns wrote:

> i wonder if this possible to subclass a list or a tuple and add more
> attributes ? also does someone have a link to how well define is own
> iterable object ?

[You tried hard]

With lists it is the standard procedure of overriding __init__() and calling
the baseclass method:

>>> class List(list):
...     def __init__(self, iterable, a):
...             list.__init__(self, iterable)
...             self.a = a
...
>>> a = List((1,2,3), "abc")
>>> a
[1, 2, 3]
>>> a.a
'abc'

Tuples are immutable and thus changes in __init__() will not affect the
tuple items. They are set in the __new__() method instead.

>>> class Tuple(tuple):
...     def __new__(cls, *args):
...             return tuple.__new__(cls, args[0])
...     def __init__(self, seq, a):
...             self.a = a
...
>>> b = Tuple((1,2,3), "abc")
>>> b
(1, 2, 3)
>>> b.a
'abc'

For a minimal iterable class, let __iter__() return self and next()
calculate the next value or raise a StopIteration exception when there are
no more values:

>>> class Iterable:
...     def __init__(self, start, maxval):
...             self.value = start
...             self.maxval = maxval
...     def __iter__(self): return self
...     def next(self):
...             if self.value > self.maxval:
...                     raise StopIteration
...             result = self.value
...             self.value *= -2
...             return result
...
>>> for n in Iterable(1, 500):
...     print n,
...
1 -2 4 -8 16 -32 64 -128 256 -512

(I've got a hunch that Iterator would have been a more appropriate name, but
you may judge on your own, see
http://www.python.org/doc/current/tut/node17.html)

Peter



More information about the Python-list mailing list