Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

strange behaviour when inheriting from tuple

1 view
Skip to first unread message

metal

unread,
Oct 11, 2009, 3:04:20 AM10/11/09
to
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

ryles

unread,
Oct 11, 2009, 5:30:43 AM10/11/09
to

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__

metal

unread,
Oct 11, 2009, 9:48:09 AM10/11/09
to

That's it. Thank you very much.

0 new messages