Is this a bug?

Peter Otten __peter__ at web.de
Tue Mar 9 18:21:20 EST 2004


Carolina Feher wrote:

>>>> def f(a):
> ...     return 5
> ...
>>>> class A(list):
> ...     g = f
> ...     def __new__(cls):
> ...             c = list.__new__(cls, [1, 2])
> ...             c.g()
> ...             return c
> ...
>>>> a = A()
>>>> a
> []
> 
> Why is an empty list returned?

Because for lists the __init__ method does the initialization:
>>> class A(list):
...     def __init__(self):
...             list.__init__(self, [1,2])
...
>>> A()
[1, 2]

whereas for tuples that woould be too late because they're immutable. 
Therefore:

>>> class B(tuple):
...     def __new__(cls):
...             return tuple.__new__(cls, [1,2])
...
>>> B()
(1, 2)
>>>

Peter




More information about the Python-list mailing list