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?