对cons中未反映的变量所做的更改

2024-04-26 07:01:31 发布

您现在位置:Python中文网/ 问答频道 /正文

代码更能说明问题:

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。Configs>;执行:使用Python控制台运行。你知道吗


Tags: 代码inimportnumpyfordefasnp
1条回答
网友
1楼 · 发布于 2024-04-26 07:01:31

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

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

在控制台中将a重新绑定到新对象时,func仍将在源文件中使用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.]

你的代码在测试.py文件。你知道吗

相关问题 更多 >