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

编程入门 行业动态 更新时间:2024-10-08 22:47:45
本文介绍了对变量所做的更改未反映在控制台中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

代码更胜一筹:

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.

更多推荐

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

本文发布于:2023-11-01 11:06:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549171.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   所做   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!