Python 2.7 更改另一个python文件中的全局变量
我计划通过导入另一个python文件来修改该文件中的全局变量。新文件似乎修改了全局变量。但是,当通过调用原始类中的函数来访问全局变量时,它仍然不会被修改。我怎样才能做到这一点?例如,Python 2.7 更改另一个python文件中的全局变量,python-2.7,global-variables,Python 2.7,Global Variables,我计划通过导入另一个python文件来修改该文件中的全局变量。新文件似乎修改了全局变量。但是,当通过调用原始类中的函数来访问全局变量时,它仍然不会被修改。我怎样才能做到这一点?例如,base_file.py定义如下: CONFIG_DICT = {'Name1': 'Value1'} def print_config(): for name, val in CONFIG_DICT.iteritems(): print 'Inside print_config - Name:%
base_file.py
定义如下:
CONFIG_DICT = {'Name1': 'Value1'}
def print_config():
for name, val in CONFIG_DICT.iteritems():
print 'Inside print_config - Name:%s and Value:%s' % (name, val)
import base_file as bf
def update_config():
for name, val in bf.CONFIG_DICT.iteritems():
print 'Before modification inside update_config - Name:%s and Value:%s' % (name, val)
bf.CONFIG_DICT = {}
bf.CONFIG_DICT['Name2'] = 'Value2'
for name, val in bf.CONFIG_DICT.iteritems():
print 'After modification inside update_config - Name:%s and Value:%s' % (name, val)
if __name__ == "__main__":
bf.print_config()
update_config()
bf.print_config()
new_file.py
定义如下:
CONFIG_DICT = {'Name1': 'Value1'}
def print_config():
for name, val in CONFIG_DICT.iteritems():
print 'Inside print_config - Name:%s and Value:%s' % (name, val)
import base_file as bf
def update_config():
for name, val in bf.CONFIG_DICT.iteritems():
print 'Before modification inside update_config - Name:%s and Value:%s' % (name, val)
bf.CONFIG_DICT = {}
bf.CONFIG_DICT['Name2'] = 'Value2'
for name, val in bf.CONFIG_DICT.iteritems():
print 'After modification inside update_config - Name:%s and Value:%s' % (name, val)
if __name__ == "__main__":
bf.print_config()
update_config()
bf.print_config()
运行new_file.py
的输出如下:
Inside print_config - Name:Name1 and Value:Value1
Before modification inside update_config - Name:Name1 and Value:Value1
After modification inside update_config - Name:Name2 and Value:Value2
###########################################################
# How Can I change this so that this yields Name2, Value2?#
###########################################################
Inside print_config - Name:Name1 and Value:Value1