subclassing 'list'

J. Cliff Dyer jcd at
Tue Jan 6 22:09:13 CET 2009

On Tue, 2009-01-06 at 12:34 -0800, akineko wrote:
> Hello everyone,
> I'm creating a class which is subclassed from list (Bulit-in type).
> It works great.
> However, I'm having a hard time finding a way to set a new value to
> the object (within the class).
> There are methods that alter a part of the object (ex. __setitem__()).
> But I couldn't find any method that can replace the value of the
> object.
> I wanted to do something like the following:
> class Mylist(list):
>     def arrange(self):
>         new_value = ....
>         list.self.__assign__.(self, new_value)
> I serached the newsgroup and found that assignment operator ('=')
> cannot be overridden because it is not an operator. But it shouldn't
> stop Python to provide a way to re-assign the value internally.


I'm not sure I understand your problem.  What I see above is an
attribute error:

AttributeError: type object 'list' has no attribute 'self'

coming from your use of list.self, but it doesn't sound like that's what
you are asking about.  Do you mean that you want to be able to specify
some sort of processing to be done when you assign to an attribute of
your object?  To do that, you need to use properties:

import math
class Circle(object):
     def __init__(self, radius=1.0):
         self._radius = radius
         self.circum = 2.0 * self._radius * math.pi

     def __get_radius(self):
         return self._radius

     def __set_radius(self,radius):
         self._radius = radius
         self.circum = 2.0 * self._radius * math.pi

     radius = property(__get_radius, __set_radius)

Then you can do:

>>> circ = Circle(2.0)
>>> print circ.radius
>>> print circ.circum
>>> circ.radius = 4.5
>>> print circ.radius
>>> print circ.circum

There are lots of good tutorials on this online.

More information about the Python-list mailing list