strange behaviour when inheriting from tuple

metal metal29a at gmail.com
Sun Oct 11 15:48:09 CEST 2009


On 10月11日, 下午5时30分, ryles <ryle... at gmail.com> wrote:
> 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)
>
> Seehttp://www.python.org/download/releases/2.2.3/descrintro/#__new__

That's it. Thank you very much.



More information about the Python-list mailing list