代码更胜一筹:
import numpy as np a = np.ones(shape=(4, 2)) def func(): for i in a: print(i)运行:
In[3]: func() [1. 1.] [1. 1.] [1. 1.] [1. 1.] In[4]: a = np.zeros(shape=(4, 2)) In[5]: func() [1. 1.] [1. 1.] [1. 1.] [1. 1.]请注意,我更改了 (a).但是,当我再次运行该功能时,没有任何变化!!详细信息:Pycharm 的最新版本.配置 > 执行:使用 Python 控制台运行.
Notice that I changed (a). But, when I run the function again, no changes!! Details: latest version of Pycharm. Configs > Execution: Run with Python console.
推荐答案我不使用 Pycharm.但我想我知道为什么.
I don't use Pycharm. But I think I know why.
当您使用 Python 控制台运行时,它应该在后台具有 from your-source-file import *.
When you Run with Python console, it should have from your-source-file import * in background.
当您在控制台中将 a 重新绑定到新对象时,func 仍将使用您的源文件中的 a,而不是 a 在控制台中.
When you rebind a to new object in console, the func will still use the a in your-source-file, not the a in console.
您可以通过显式 from your-source-file import * 进行尝试,然后执行其余操作来验证它.我自己在电脑上查过.
You can have a try by explicitly from your-source-file import * and take the rest of actions to verify it. I have checked it on my computer by myself.
如果您想了解原因,可以阅读4.执行模型:名称解析 — Python 3.7.3 文档,并确保您理解这一点:
If you want understand why, you can read 4. Execution model: resolution-of-names — Python 3.7.3 documentation, and make sure you understand this:
在代码块中使用名称时,将使用最近的封闭作用域对其进行解析.代码块可见的所有此类范围的集合称为块的环境.
When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.
我在 ipython 中的尝试:
My try in ipython:
In [2]: from test import * In [3]: func() [1. 1.] [1. 1.] [1. 1.] [1. 1.] In [4]: a = np.zeros(shape=(4, 2)) In [5]: func() [1. 1.] [1. 1.] [1. 1.] [1. 1.] In [6]: def func(): ...: for i in a: ...: print(i) ...: In [7]: func() [0. 0.] [0. 0.] [0. 0.] [0. 0.]和
In [1]: from auto_audit_backend.test_np import * In [2]: func() [1. 1.] [1. 1.] [1. 1.] [1. 1.] In [3]: a[0][0] = 666 In [4]: func() [666. 1.] [1. 1.] [1. 1.] [1. 1.] In [5]: a = np.zeros(shape=(4, 2)) In [6]: func() [666. 1.] [1. 1.] [1. 1.] [1. 1.]使用 test.py 文件中的代码.
with your code in test.py file.
更多推荐
对变量所做的更改未反映在控制台中
发布评论