subclassing list and adding other variables ?

GrelEns grelens at NOSPAMyahoo.NOTNEEDEDfr
Thu Mar 11 15:49:56 EST 2004


hello,

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 ?

what i was expecting was something like :

>>> t = Test('anAttributeValue', ['el1', 'el2'])
>>> t.anAttribute
'anAttributeValue'
>>> for x in t:
       print x
el1
el2

and below are some real unsuccessful tests :

>>> class Test(tuple):
 def __init__(self, a, alist):
  self.a = a
  self = tuple(alist)


>>> t = Test(1, (1,2,3))

Traceback (most recent call last):
  File "<pyshell#486>", line 1, in -toplevel-
    t = Test(1, (1,2,3))
TypeError: tuple() takes at most 1 argument (2 given)
>>> class Test(tuple):
 def __init__(self, (a, alist)):
  self.a = a
  self = tuple(alist)


>>> t = Test((1, (1,2,3)))
>>> t.a
1
>>> t.a = 2
>>> t.a
2
>>> len(t)
2
>>> t
(1, (1, 2, 3))
>>> t[2]

Traceback (most recent call last):
  File "<pyshell#495>", line 1, in -toplevel-
    t[2]
IndexError: tuple index out of range
>>> t[1]
(1, 2, 3)
>>> class Test(tuple):
 def __init__(self, (a, alist)):
  self.__init__(tuple(alist))
  self.a = a


>>> t = Test((1, (1,2,3)))

Traceback (most recent call last):
  File "<pyshell#500>", line 1, in -toplevel-
    t = Test((1, (1,2,3)))
  File "<pyshell#499>", line 3, in __init__
    self.__init__(tuple(alist))
  File "<pyshell#499>", line 2, in __init__
    def __init__(self, (a, alist)):
ValueError: unpack tuple of wrong size
>>> class Test(tuple):
 def __init__(self, alist, a = None):
  self.__init__(tuple(alist))
  self.a = a


>>> t = Test((1,2,3), 4)

Traceback (most recent call last):
  File "<pyshell#503>", line 1, in -toplevel-
    t = Test((1,2,3), 4)
TypeError: tuple() takes at most 1 argument (2 given)
>>> class Test(tuple):
 def __init__(self, (alist, a = None)):
  self.__init__(tuple(alist))
  self.a = a

SyntaxError: invalid syntax
>>>
>>> class Test(list):
 def __init__(self, (a, alist)):
  self.a = a
  self = tuple(alist)


>>> t = Test((4, (1,2,3)))
>>> t
[]
>>> class Test(list):
 def __init__(self, (a, alist)):
  self.a = a
  self = alist


>>> t = Test((4, (1,2,3)))
>>> t
[]
>>> t.a
4
>>> len(t)
0
>>> class Test(list):
 def __init__(self, a, alist):
  self.a = a
  self = alist


>>> t = Test(4, (1,2,3))
>>> t
[]
>>> t.a
4
>>> class Test(list):
 def __init__(self, a, alist):
  self.a = a
  self.__init__(alist)


>>> t = Test(4, (1,2,3))

Traceback (most recent call last):
  File "<pyshell#523>", line 1, in -toplevel-
    t = Test(4, (1,2,3))
  File "<pyshell#522>", line 4, in __init__
    self.__init__(alist)
TypeError: __init__() takes exactly 3 arguments (2 given)





More information about the Python-list mailing list