modifying __new__ of list subclass
Steven Bethard
steven.bethard at gmail.com
Mon Aug 14 23:56:13 EDT 2006
Ken Schutte wrote:
> I want an int-derived class that is initilized to one greater than what
> it's constructor is given:
>
> class myint(int):
> def __new__(cls, intIn):
> newint = int(intIn+1)
> return int.__new__(cls, newint)
Or simply:
class myint(int):
def __new__(cls, int_in):
return int.__new__(cls, int_in + 1)
> Now, lets say I want a list class that
> creates a list of strings, but appends "_" to each element. I try the
> same thing:
>
> class mylist(list):
> def __new__(cls, listIn):
> newlist = list()
> for i in listIn:
> newlist.append(str(i) + "_")
> print "newlist: ", newlist
> return list.__new__(cls, newlist)
The __new__ method is for immutable types. So things like str and int
do their initialization in __new__. But for regular mutable types, you
should do your initialization in __init__::
class mylist(list):
def __init__(self, list_in):
for item in list_in:
self.append(str(item) + '_')
STeve
More information about the Python-list
mailing list