2014-11-06 67 views
0

你会如何描述下面的代码是怎么回事?如何解释“import my_module”和“from my_module import my_str”之间的区别?

my_module.py:

my_dict = { "key": "default value" } 
my_str = "default" 

Python解释:

>>> from my_module import my_dict, my_str 
>>> import my_module 
>>> 
>>> assert my_dict == { "key": "default value" } 
>>> assert my_module.my_dict == { "key": "default value" } 
>>> assert my_str == "default string" 
>>> assert my_module.my_str == "default string" 
>>> 
>>> my_dict["key"] = "new value" 
>>> my_str = "new string" 
>>> 
>>> assert my_dict == { "key": "new value" } 
>>> assert my_module.my_dict == { "key": "new value" } # why did this change? 
>>> assert my_str == "new string" 
>>> assert my_module.my_str == "default string" # why didn't this change? 
>>> 
>>> my_module.my_dict["key"] = "new value 2" 
>>> my_module.my_str = "new string 2" 
>>> 
>>> assert my_dict == { "key": "new value 2" } # why did this change? 
>>> assert my_module.my_dict == { "key": "new value 2" } 
>>> assert my_str == "new string" # why didn't this change? 
>>> assert my_module.my_str == "new string 2" 
>>> 
>>> my_dict = { "new_dict key" : "new_dict value" } 
>>> assert my_dict == { "new_dict key": "new_dict value" } 
>>> assert my_module.my_dict == { "key": "new value 2" } # why didn't this change? 

回答

0

my_module.my_strmy_str对象在my_module命名空间,和修改my_module.my_str修改该对象。

from my_module import my_str在本地命名空间中创建一个my_str对象,从my_module.my_str对象复制而来。修改my_str会修改本地名称空间中的对象,但不会修改对象my_module.my_str

my_dict是在my_module.my_dict的本地命名空间中的参考。因为它是对可变对象(字典)的引用,所以对my_dict所做的更改会影响my_module.my_dict,反之亦然。

相关问题