[Tutor] Beginner question (variables, namespaces...)

Alan Gauld alan.gauld at freenet.co.uk
Sat Apr 8 09:52:47 CEST 2006


Others have provided workarounds I'll attempt to answer the
rationale part...

> Why is it that when one variable is assigned a value in terms of another
> variable, assigning a new value to the first doesn't change the value of 
> the
> second?

Python variables are just names that refer to a value.
The value can be any kind of object that python recognises but
it is a single value.

When you assign an expression  to a variable Python evaluates the
current value of the expression before assigning it, it does not
understand the concept of an expression as a value in its own right.
The only way to store an expression is to place it in a function as
the others have shown. The function can then be cxalled as needed,
but it must be called explicitly, you cannot call it by implication
when one of the terms of the expression changes.

There is a way to fake this a little using properties of a class.
If you create a class that has all your variables as properties, then
you can write get/set methods for those properties such that when
changed they automatically update the other properties, thus
rippling the changes through your system. But using properties
like this is a slightly esoteric technique in Python.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list