overriding a tuple's __init__

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Aug 18 04:24:21 EDT 2003


Simon Burton <simonb at webone.com.au> wrote in 
news:pan.2003.08.18.07.37.44.108933 at webone.com.au:

>>>> class pair(tuple):
> ...   def __init__(self,a,b):
> ...     tuple.__init__(self, (a,b) )
> ... 
>>>> a=pair(1,2)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: tuple() takes at most 1 argument (2 given)
>>>> 
> 
> What gives? (yes it works with a list, but i need immutable/hashable)

You need to override __new__ instead of __init__:

>>> class pair(tuple):
	def __new__(cls, a, b):
		return tuple.__new__(cls, (a,b))

Tuples really are immutable, so their value has to be set by the 
constructor __new__ rather than the initialiser __init__. The same applies 
if you wanted to subclass numbers.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list