Connecting Tech Pros Worldwide Help | Site Map

Re: python bug when subclassing list?

  #1  
Old November 12th, 2008, 02:25 AM
Steve Holden
Guest
 
Posts: n/a
Hamish McKenzie wrote:
Quote:
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?
>
Vector(1, 2, 3) fails for exactly the same reasons as list:
Quote:
Quote:
Quote:
>>list(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list() takes at most 1 argument (3 given)

So the behavior you want cannot be inherited from list, since list
doesn't implement that behavior!

As toy our assertion that you can subclass tuple that way, I am inclined
to doubt it because of this:
Quote:
Quote:
Quote:
>>tuple(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: tuple() takes at most 1 argument (3 given)

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: python bug when subclassing list? Ethan Furman answers 0 November 12th, 2008 12:55 AM
Weird behavior with lexical scope mrstevegross answers 9 November 7th, 2008 09:25 PM
python-dev Summary for 2006-07-16 through 2006-07-31 steven.bethard@gmail.com answers 0 August 15th, 2006 06:25 AM
python-dev Summary for 2005-12-01 through 2005-12-15 Tony Meyer answers 0 January 20th, 2006 04:55 AM