floatref

Tino Wildenhain tino at wildenhain.de
Wed Jul 14 16:22:59 EDT 2010


Am 13.07.2010 19:26, schrieb Roald de Vries:
 > Hi all,
 >
 > I have two objects that should both be able to alter a shared float. 
 > So i need something like a mutable float object, or a float reference 
 > object. Does anybody know if something like that exists? I know it's 
 > not hard to build, but I have a feeling that there should be a
 > standard solution to it.

Nice question to reflect our understanding of the basics of this language.

 From what I know, we have the terms:

- reference
- name

(pointer is not really used beside from indices into lists or such)

I see it this way: you have named and unnamed references to objects. 
This means you
can bind any number of names to an object as well as reference the 
object in a list, tupe or set:

 >>> (1,2,3) # unnamed references to int objects 1,2 and 3

 >>> a=(1,2,3)[1]  # binds a to tuple element #1 (int 2 object)

 >>> b=a # now a and b are bound to the same int 2 object

So back to your question:

 >>> a=b=1.0 # binds the names a and b to the same float object 1.0

 >>> a,b
(1.0, 1.0)

now, there is no way to alter the float object since it is immutable (as 
there are str, unicode, int, long, tuple...)

 >>> a+=0.5
 >>> a,b
(1.5, 1.0)

now you see even the "in place" addition creates a new object and
binds the name to it.

What you'd need to do would probably wrapping the float value into a
class where you can simulate a mutable float by providing a constant
name or reference for it within the class.

For example:

 >>> a=b=[1.0]
 >>> a[0]+=0.5
 >>> a,b
([1.5], [1.5])

HTH
Tino







More information about the Python-list mailing list