Reputation: 1
I want to make i
into 3 in file s2.py, but it keeps becoming 1.
i=1
class a():
def f():
global i
i = 3
from s1 import *
a.f()
print(i)
Upvotes: 0
Views: 67
Reputation: 1
Reimport the variable after calling the method:
i = 1
class a():
def f():
global i
i += 3
import s1
s1.a.f()
print(s1.i)
Upvotes: 0
Reputation: 1
I believe you are referencing the local variable i
and aren't referencing the instance of i
in the class. Try this.
print(a.i)
Upvotes: 0
Reputation: 86
#s1.py
i=1
class a():
def f():
global i
i += 3
#s2.py
import s1
s1.a.f()
print(s1.i)
Upvotes: 0
Reputation: 532538
Every module has its own global scope, and Python is lexically scoped, meaning a.f
refers to the global scope of s1
no matter where it is called from. i
is initialized to the value of s1.i
, but is otherwise independent of it. Changes to s1.i
do not affect s2.i
.
Upvotes: 1
Reputation: 41
You have to re-import your variable after calling your method if you want to see any changes made.
#s1.py
i=1
class a():
def f():
global i
i = 3
#s2.py
from s1 import *
a.f()
from s1 import i
print(i)
Upvotes: 0