在python编程中,一般使用global 关键字来定义全局变量,但是发现 global 关键字在涉及多个文件时,好像存在问题。
比如,单个文件下用global定义使用全局变量的情况 ,看下面的代码
#-*-coding: utf-8 -*-#from data_def import *
distance=34
classtest(object):def __init__(self):pass
#在类里面改变全局变量的值
defchange_1(self):globaldistance
distance=90
print("distance in class:", distance)#输出全局变量的值
defprint_value(self):globaldistanceprint("distance in class:", distance)#在函数里面使用和打印全局变量的值
deffunction_test():globaldistanceprint("global value in function", distance)
distance=234
print("global value in function",distance)
function_test()#在函数里面使用和改变全局变量的值 34->234
t=test()
t.print_value()#在类里面打印全局变量的值 234
t.change_1() #在类里面改变全局变量的值 234->90
程序运行结果如下:全局变量运行正确
global value in function 34
global