subclassing list and adding other variables ?

GrelEns grelens at NOSPAMyahoo.NOTNEEDEDfr
Mon Mar 15 11:16:50 EST 2004


"Peter Otten" <__peter__ at web.de> a écrit dans le message de news:
c2qr32$j1n$01$1 at news.t-online.com...
> 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 ?
>
> 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'

thanks, so i supposed that this is a correct way to do :

>>> class List(list):
 def __init__(self, v = None):
  self.v = v
 def load(self, values):
  list.extend(self, values)
 def gets(self):
  return list(self)

>>> l = List(5)
>>> l.load([1,2,3])
>>> l
[1, 2, 3]
>>> l.gets()
[1, 2, 3]
>>> type(l.gets())
<type 'list'>
>>> type(l)
<class '__main__.List'>

BTW while i think i get it with the list.extend(self, values) which is i
suppose

super_class.method_from_super_class(my_current_instance, *ohers_args)

i feel quite unhappy with the return list(self) which for me is rather a
call to the builtin function list() upon the current instance , how could i
write this particular :

super_class.attribute_containing_content_of(my_current_instance)

also, which are the method to overwrite for a class subclassing a list to
automatically call the load() method if the list is empty ?

thx for your help.





More information about the Python-list mailing list