strange behaviour when inheriting from tuple

M

metal

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
 
R

ryles

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__
 
M

metal

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top