Sublassing tuple works, subclassing list does not
Hrvoje Niksic
hniksic at xemacs.org
Wed Mar 31 07:07:55 EDT 2010
"Frank Millman" <frank at chagford.com> writes:
>>>> class MyList(list):
> ... def __new__(cls, names, values):
> ... for name, value in zip(names, values):
> ... setattr(cls, name, value)
> ... return list.__new__(cls, values)
Did you really mean to setattr the class here? If I'm guessing
your intentions correctly, it should be:
def __new__(cls, names, values):
self = list.__new__(cls, values)
for name, value in zip(names, values):
setattr(self, name, value)
return self
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: list() takes at most 1 argument (2 given)
>>>>
>
> I can find a workaround, but I would be interested to know the reason
> why it does not work.
Because you didn't define __init__, so MyList inherited the one from
list, and it has a different signature to what you're calling it with.
Simply add an __init__ with the proper signature, and the proper upcall
to list.__init__:
def __init__(self, names, values):
list.__init__(self, values)
But if you're doing that, you don't need __new__ at all. Simply
override __init__ and place your setattr loop there:
>>> class MyList(list):
... def __init__(self, names, values):
... for name, value in zip(names, values):
... setattr(self, name, value)
... list.__init__(self, values)
...
>>> MyList(['a'], [1])
[1]
>>> _.a
1
More information about the Python-list
mailing list