对变量所做的更改未反映在控制台中

Changes made to variable not reflected in console

代码说话更好:

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 控制台。

我不使用 Pycharm。但我想我知道为什么。

当您 运行 使用 Python 控制台时,它应该有 from your-source-file import * 在后台。

当您将 a 重新绑定到控制台中的新对象时,函数仍将在 your-source-file 中使用 the a,而不是在控制台中使用 the a

您可以通过显式 from your-source-file import * 进行尝试,然后执行其余操作来验证它。我自己在电脑上查过了

如果你想明白为什么,你可以阅读4. Execution model: resolution-of-names — Python 3.7.3 documentation,并确保你理解这一点:

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 中的尝试:

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 文件中使用您的代码。