I have the following code:
one.py
import two as t
t.test1()
t.test2()
two.py
class test_class():
def __init__(self,arg):
print("created obj name is {}".format(arg))
self.name = arg
non_global ="initial global"
obj = test_class("test name")
def test1():
print("\t in test 1")
print (obj.name)
global non_global # wont work without global keyword, value still refers to "initial value"
print(non_global) # initial value
obj.name = "changed"
#non_global = "changed global"
def test2():
print("\tin test 2")
print(obj.name)
print(non_global)
The result is:
created obj name is test name
in test 1
test name
initial global
in test 2
changed
changed global
if I change in test1()
to:
def test1():
print("\t in test 1")
print (obj.name)
#global non_global # wont work without global keyword, value still refers to "initial value"
print(non_global) # initial value
obj.name = "changed"
non_global = "changed global"
I get the error UnboundLocalError: local variable 'non_global' referenced before assignment
on the print line.
If I comment non_global = "changed global"
the error goes away.
my questions is:
Why is this happening for non_global
and not for obj
? I am on python 3.5