srinivasan srinivas wrote:
Hi,
I have a class which is a subclass of builtin-type list.

#------------------------------------------------------------------------------
class clist(list):
    def __new__(cls, values, ctor):
        val = []
        for item in values:
            item = ctor(item)
            val.append(item)
self = list.__new__(cls, val)
        self.__values = val
        self.__ctor = ctor
        return self

A subclass of list should populate the list in __init__, not __new__, usually by calling list.__init__, as lists are mutable and subclasses thereof should be too.

class clist(list):
     def __init__(self, values, ctor):
         list.__init__(self, map(ctor, values))
         self.__ctor = ctor

clist1 = clist((1,2,3),str)
clist2 = clist((1,2,3), float)
alist1 = [clist1,clist2]
print(alist1)
#[['1', '2', '3'], [1.0, 2.0, 3.0]]

from copy import deepcopy
alist2 = deepcopy(alist1)
print(alist2)
#[['1', '2', '3'], [1.0, 2.0, 3.0]]

print(alist1[0] is alist2[0])
#False - ie, inner clist was copied

I omitted your __values attribute as redundant with the value of the clist itself. Since clist is not a mixin class, double underscores for name-mangling are not needed.

Unless you make use of _ctor in other methods, initializing regular lists with 'list(map(ctor,values)) would work as well.

Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to