overriding a tuple's __init__

Bengt Richter bokr at oz.net
Tue Aug 19 00:01:58 CEST 2003


On 18 Aug 2003 10:27:47 -0400, aahz at pythoncraft.com (Aahz) wrote:

>In article <bhq648$s4t$1 at slb3.atl.mindspring.net>,
>Andrew Dalke <adalke at mindspring.com> wrote:
>>
>>The problem is the immutability.  This one one of the
>>new changes in 2.3 I still don't fully understand, but I do
>>know the solution is __new__
>>
>>>>> class pair(tuple):
>>...  def __new__(self, a, b):
>>...   return tuple((a, b))
>>...
>>>>>
>>>>> pair(2,3)
>>(2, 3)
>>>>> x=_
>>>>> type(x)
>><type 'tuple'>
>>>>>
>>
>>That should give you some pointers for additional searches.
>
>This works better:
>
>class pair(tuple):
>    def __new__(cls, *args):
>        return tuple.__new__(cls, args)

so far, just

    class pair(tuple): pass

should do it, no? Unless you want to take the name as suggesting that
length 2 should be enforced. Don't know what other methods are planned,
but ISTM you get the vanilla __new__ for free. Or am I missing something?

Regards,
Bengt Richter




More information about the Python-list mailing list