strange behaviour when inheriting from tuple
ryles
rylesny at gmail.com
Sun Oct 11 05:30:43 EDT 2009
On Oct 11, 3:04 am, metal <metal... at gmail.com> wrote:
> Environment:
>
> PythonWin 2.5.4 (r254:67916, Apr 27 2009, 15:41:14) [MSC v.1310 32 bit
> (Intel)] on win32.
> Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin'
> for further copyright information.
>
> Evil Code:
>
> class Foo:
> def __init__(self, *args):
> print args
>
> Foo(1, 2, 3) # (1, 2, 3), good
>
> class Bar(tuple):
> def __init__(self, *args):
> print args
>
> Bar(1, 2, 3) # TypeError: tuple() takes at most 1 argument (3 given)
>
> what the heck? I even didn't call tuple.__init__ yet
When subclassing immutable types you'll want to override __new__, and
should ensure that the base type's __new__ is called:
__ class MyTuple(tuple):
__ def __new__(cls, *args):
__ return tuple.__new__(cls, args)
__ print MyTuple(1, 2, 3)
(1, 2, 3)
See http://www.python.org/download/releases/2.2.3/descrintro/#__new__
More information about the Python-list
mailing list