By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,656 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

Re: python bug when subclassing list?

P: n/a
Hamish McKenzie wrote:
I want to write a Vector class and it makes the most sense to just
subclass list. I also want to be able to instantiate a vector using either:

Vector( 1, 2, 3 )
OR
Vector( [1, 2, 3] )

so I have this:

class Vector(list):
def __new__( cls, *a ):
try:
print a
return list.__new__(cls, a)
except:
print 'broken'
return list.__new__(cls, list(a))

doing Vector( 1, 2, 3 ) on this class results in a TypeError – which
doesn’t seem to get caught by the try block (ie “broken” never gets
printed, and it never tries to

I can do pretty much the exact same code but inheriting from tuple
instead of list and it works fine.

is this a python bug? or am I doing something wrong?

thanks,
-h.
Greetings!

I am not sure of the proper way to fix this issue, but the problem you
have is that lists do not have a __new__ method:

--list
<type 'list'>

--list.__new__
<built-in method __new__ of *type object* at 0x1E1D6A78>

--list.__init__
<slot wrapper '__init__' of *'list' objects*>

Changing the __new__ to __init__ at least gets your code to run, but
then you have this:

--vector.Vector(1, 2, 3)
(1, 2, 3)
broken
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "vector.py", line 15, in __init__
return list.__new__(cls, list(a))
TypeError: list.__new__(X): X is not a type object (Vector)

Good luck in your journey!
~ethan~
Nov 12 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.