Problem with imported variable

carole valentin carole_valentin at yahoo.fr
Fri Nov 2 09:58:37 CET 2001


Christopher Barker wrote:
>carole valentin wrote:
>> I have a little question:
>> I have 2 classes "Class1" and "Class2" and several
>> functions in each class. The Class1 is in the file
>> "File1" and the Class2 is in another file "File2". 
>> At the beginning of the File1, I import the File2:
>> from File2 import *
>> 
>> In the Class2, I create a variable with a specific
>> value. When the program is running, I modify the
>> value of this variable in the other class (Class1)
>> and then I want to read the new value of the 
>> variable farther in the code of the Class2.
>> The problem is that the value does not change in
the
>> File2 (Class2). Moreover, as the 2 classes are not 
>> in the same files, the global statement does not 
>> change the problem.
>> Does someone have an idea?
>> Thanks for your help!
>
> Someone else may be able to figure out what you want

> to do, but I'm lost. Try posting a very small 
> version of your attempt to do what you
> want, and we'll probably be able to help you.


Here is a very small version of the program:

# ------- File1.py -------
global var
var = 2
print "var1 = ", var  # => var1 = 2

from File2 import *

class Class1:
    def function1(self):
        global var
        var = 3
        print "var3 = ", var # => var3 = 3


first_class = Class1()
first_class.function1()
second_class = Class2()
second_class.function2()
print "var6 = ", var  # => var6 = 3 , But I would like
that var6 = 4 !!!

# ------- File2.py -------
from File1 import var
# if I don't put this line, it says that the variable
var does not exist

print "var2 = ", var  # => var2 = 2

class Class2:
    def function2(self):
        global var
        print "var4 = ", var  # => var4 = 2 , But I
would like that var4 = 3 !!!
        var = 4
        print "var5 = ", var  # => var5 = 4
# -----------------------



Shankar wrote:
>Actually, I too faced the same problem today. 
>I struggled for nearly an hour.
>If I all code in the same file, 
>everything seems to work. But, in the
>name of modularity, when I tried to split my code 
>neatly into 2 different classes, variables of class2
>set by methods of class2, but accessed from methods
>of class1 seem not to get updated.

That is exactly my problem !!!

Carole.


___________________________________________________________
Do You Yahoo!? -- Une adresse @yahoo.fr gratuite et en français !
Yahoo! Courrier : http://courrier.yahoo.fr




More information about the Python-list mailing list