导入模块的方法是否会改变全局变量的性质?

时间:2019-07-17 16:28:52

标签: python python-3.x

访问在导入的模块中定义的全局变量。导入它们的方式似乎会影响模块中声明的变量的全局或局部性质。


在下面的代码中,我尝试了“ import hello”,并且按预期方式工作,该全局变量在hello.py模块中定义,可以通过“ hello.addressee”或通过诸如hello.changeAddress(“ Ged”)的函数访问得到改变并按预期使用。


尝试“从hello import *”或通过命名要从“ hello import world,changeAddress,addressee”导入的函数和变量命名,全局变量addressee在某些情况下会成为局部变量。

** hello.py:**

# global variable decl
addressee = 'world'

def world():
    print("Hello %s from address %s" % (addressee, hex(id(addressee))))
def changeAddress(userName):
    addressee = userName
    print("changeAddress %s to %s" %( hex(id(addressee)), addressee))

main.py:

# please don't remind me that this is a problem. we all have code 
# to maintain
from hello import * 

# I tried this method too, but got the same results
#from hello import world, changeAddress 
#from hello import addressee

world() 
print("1: addressee = ", hex(id(addressee)))
addressee = 'Sammy'
print("2: addressee = ", hex(id(addressee)))
world()

changeAddress('jace')
print("3: Changed addressee %s to %s" %( hex(id(addressee)), addressee))
world()

输出:

Hello world from address 0x3e97aa0
1: addressee =  0x3e97aa0            <-- pointed at value in hello.py
2: addressee =  0x3e97c40            <-- changed as expected on assignment
Hello world from address 0x3e97aa0   <-- uses the value from hello.py again
changeAddress 0x3e97be0 to jace      
3: Changed addressee 0x3e97c40 to Sammy 
Hello world from address 0x3e97aa0    

因此,我希望第一个调用hello.world()可以打印“ hello world”,第二个可以打印“ hello sammy”,第三个可以打印“ hello Jace”。

根据我得到的输出,看来main.py有一个本地变量addressee,hello.py中的changeAddress()也是如此。但是hello.py中的world()获得了全局变量收件人。

有人可以解释吗?

0 个答案:

没有答案