promoting [] by superclass?

Robert Brewer fumanchu at amor.org
Tue Jun 8 18:10:20 EDT 2004


Jim Newton wrote:
> Basically i'd like the Pair.__init__ in the case of Pair(1,2,3,4,5),
> to set self[0]=1, and self[1] = Pair(2,3,4,5) in some iterative
> way.

Sure, just perform that split in your __init__ method, and override
__new__ to match arguments:

>>> class Pair(list):
... 	def __new__(cls, *args):
... 		return list.__new__(cls)
... 	
... 	def __init__(self, *args):
... 		args = list(args)
... 		if len(args) > 2:
... 			self[:] = args[0], Pair(*args[1:])
... 		else:
... 			self[:] = args[:]
... 			
>>> Pair(1, 2, 3)
[1, [2, 3]]
>>> Pair()
[]
>>> Pair(1)
[1]
>>> Pair(1, 2, 3, 4, 5, 6)
[1, [2, [3, [4, [5, 6]]]]]


ISTR you're somewhat new to Python (?), so I'll just quickly add that:

1) [i:j] is a slice of a list. i and j default to the endpoints; for
example, args[1:] gives you all items in a list except the first one.
http://docs.python.org/ref/slicings.html
2) *args is a way to pass a variable number of arguments.
http://docs.python.org/ref/function.html


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list