简体   繁体   中英

How to explain difference between “import my_module” and “from my_module import my_str”?

How would you describe what is going on in the following code?

my_module.py :

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

Python interpreter:

>>> 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 refers to the my_str object in the my_module namespace, and modifying my_module.my_str modifies that object.

from my_module import my_str creates a my_str object in the local namespace, copied from the my_module.my_str object. Modifying my_str modifies the object in the local namespace, but does not modify the my_module.my_str object.

my_dict is a reference in the local namespace to my_module.my_dict . Because it's a reference to a mutable object (a dictionary), changes made to my_dict affect my_module.my_dict and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM