![](/img/trans.png)
[英]How to import own module for mocking? (import error: no module named my_module!)
[英]How to explain difference between “import my_module” and “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?
my_module.my_str
引用my_module
命名空间中的my_str
对象,修改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
,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.