python - Can't Access Global Variable in Mixin -
i cannot write global variable in following program. can please give me solution this? note var
variable must in other file mod2.py
, mod3.py
in mod1.py
var = 5
in mod2.py
from mod1 import * def foo(newvalue): global var print('foo: %d' % var) var = newvalue print('before: %d' % var) foo(2) print('after: %d' % var)
in mod3.py
from mod2 import * foo(3) print('var: %d' % var)
the result when running mod3.py
is
before: 5 foo: 5 after: 2 foo: 2 var: 2
but expect be
before: 5 foo: 5 after: 2 foo: 2 var: 3
i not want solution using import modx.py
it has fact importing variables not might think does:
from mod1 import var
is same as
import mod1 var = mod1 # creates new variable
whereas can't explain what's going in code, can changing imports be:
import mod1
and referring var (without global now) as
mod1.var
problem solved.
mod2.py
:
import mod1 def foo(newvalue): print('foo: %d' % mod1.var) mod1.var = newvalue print('before: %d' % mod1.var) foo(2) print('after: %d' % mod1.var)
mod3.py
:
import mod1 mod2 import * foo(3) print('var: %d' % mod1.var)
output:
before: 5 foo: 5 after: 2 foo: 2 var: 3
please take time go through http://www.python.org/dev/peps/pep-0008/; few of things recommends:
* avoid wildcard imports (`from <module> import *`) various problems introduce * module names should `lowercase`
furthermore, global variables not considered good, , there's way around them; see why global variables evil?.
Comments
Post a Comment