Change global variable across class in python -
i trying make change global variable across classes. here code:
file main.py
import class2 class first: def changea(self): global print += 2 print test0 = first() test1 = class2.second() test2 = first() test3 = class2.second() test0.changea() test1.changea() test2.changea() test3.changea()
file class2.py
a = 1 class second: def changea(self): global print += 1 print
but returns error: global name 'a' not defined. there proper way access , change global variable across files in python? in advance
global variables don't exist in python.
the global
statement misnomed statement. means variable module's variable. there no such thing global namespace in python.
if want modify variable multiple modules must set attribute:
import module module.variable = value
doing simple assignment create or modify module's variable. code
from module import variable variable = value
simply shadows value of variable
imported module
creating new binding identifier module
's variable
value not changed.
in summary: no there no way achieve want (although want bad practice anyway, , should try use different solution).
Comments
Post a Comment