Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中更改导入模块中的变量(和因变量)_Python_Python 2.7 - Fatal编程技术网

在Python中更改导入模块中的变量(和因变量)

在Python中更改导入模块中的变量(和因变量),python,python-2.7,Python,Python 2.7,python\u import\u test2.py文件: AAA = 'test2' BBB = AAA + '_BBB' def showBBB(): print AAA print BBB AAA = 'test2' def showBBB(): print AAA BBB = AAA + '_BBB' print BBB python\u import\u test1.py文件: import python_import_test2 as t

python\u import\u test2.py文件:

AAA = 'test2'
BBB = AAA + '_BBB'
def showBBB():
    print AAA
    print BBB
AAA = 'test2'

def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB
python\u import\u test1.py文件:

import python_import_test2 as testimport
testimport.AAA = 'test1'
testimport.showBBB()`
作为一个例外,我得到:

test1
test2_BBB
如何获得:

test1
test1_BBB

这是因为,在重新初始化AAA后,该值未分配给BBB。使用语句导入时:

    import python_import_test2 as testimport
AAA的值='test2'

BBB的值='test2_BBB'

然后重新初始化AAA

现在,AAA的值='test1'

BBB的值='test2_BBB'

这就是你得到的

您可以在函数定义中初始化BBB以获得所需的结果

python\u import\u test2.py文件:

AAA = 'test2'
BBB = AAA + '_BBB'
def showBBB():
    print AAA
    print BBB
AAA = 'test2'

def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB

这是因为,在重新初始化AAA后,该值未分配给BBB。使用语句导入时:

    import python_import_test2 as testimport
AAA的值='test2'

BBB的值='test2_BBB'

然后重新初始化AAA

现在,AAA的值='test1'

BBB的值='test2_BBB'

这就是你得到的

您可以在函数定义中初始化BBB以获得所需的结果

python\u import\u test2.py文件:

AAA = 'test2'
BBB = AAA + '_BBB'
def showBBB():
    print AAA
    print BBB
AAA = 'test2'

def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB

由于
BBB
python\u import\u test2.py
中是一个全局变量,因此当您导入该模块时,python计算全局变量,使其成为
test2\u BBB
,然后您没有更改它,只是更改了
AAA

如果要更改该变量,可以在函数范围内进行更改

def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB

请注意,python中的所有内容都是关于运行时的,因此在您不运行函数之前,python不会执行它,当您在重新分配
AAA
后调用该函数时,python将使用新变量运行该函数。

因为
BBB
python\u import\u test2.py中的全局变量,所以当您导入该模块时,python会计算全局变量,使其成为
test2\u BBB
,然后您没有更改它,刚刚更改了
AAA

如果要更改该变量,可以在函数范围内进行更改

def showBBB():
    print AAA
    BBB = AAA + '_BBB'
    print BBB

请注意,python中的所有内容都是关于运行时的,因此在您不运行函数之前,python不会执行它,当您在重新分配
AAA
后调用该函数时,python将使用新变量运行它。

您可以在函数内部而不是之前分配
BBB
,您可以在函数内部而不是之前分配
BBB