Setting "value" of an int-derived class

Diez B. Roggisch deets at nospam.web.de
Sat Sep 2 19:23:18 EDT 2006


Ken Schutte schrieb:
> Lets say I want an integer class that lets you attach arbitrary 
> attributes.  I can simply do:
> 
> class foo(int): pass
> 
> x = foo(5)
> x.text = "okay"
> print x, x.text   # prints "5 okay"
> 
> So, that's good.  But, how can I change the value of x from 5 to 
> something else, without creating a new instance?
> 
> I suppose I could create a function that creates a new "foo" and copies 
> its attributes, but is there a more direct way?  Is the value "5" stored 
> in some special attribute I can just directly modify?

You can't do that - the base class is immutable. Subclassing doesn't 
change that.

What you can do of course in to create a class foo that will store its 
value in an attribute, and overload the arithmetic operators and methods 
like __int__, __long__ and __float__.

Diez



More information about the Python-list mailing list