gpt4 book ai didi

python - 如何在 IPython 中使用全局变量

转载 作者:行者123 更新时间:2023-11-28 17:46:50 24 4
gpt4 key购买 nike

IPython 如何处理局部变量?我有这个函数可以在 Python shell 中运行,但不能在 IPython shell 中运行。

def change(key,value):
global aname
global alist
alist.append(key)
aname.extend(value)

我在 for 循环中使用它,它正在从 JSON 和其他 .txt 文件中读取输入,并将键和值添加到列表中,然后另一个函数使用该列表来保存到数据库。如果我不这样做,它会很难看,并且会在我的循环中使用索引。

[change(key,value) for key,value in jsondata.itervalues()]

def storeindatabase():
do_sothing to the list aname and store
do_sothing to the alist and store

最佳答案

Beforeword: in the last couple of months this answer has been downvoted considerably. I apology if my words might seem a bit rough, but I insist globals are really harmful, as explained in the documentation linked below. If you consider downvoting further down this answer, please read the documentation and elaborate why you disagree with what's below. To quote an answer linked below: "The reason they are bad is that they allow functions to have hidden (non-obvious, surprising, hard-to-detect) side effects, leading to an increase in complexity, potentially leading to Spaghetti code."

  1. 使用globals 很可能意味着错误的工程。如果你需要一个全局的,那意味着你需要重新设计你的代码。在 Python 中更是如此。
  2. 当你真的想要使用全局(也许是唯一可接受的情况:单例,虽然在 python 中,你只会将单例的范围比你使用它的地方更全局......) ,您需要将您的变量声明为全局变量,然后为其赋予一个值。

例如:

global bar
bar = []
def foobar():
bar.append('X')

RTFM:


关于 IPython 部分,我的示例确实有效:

In [1]: global bar

In [2]: bar = []

In [3]: def foo():
...: bar.append(3)
...:

In [4]: foo()

In [5]: foo()

In [6]: foo()

In [7]: bar
Out[7]: [3, 3, 3]

这是另一个例子,它表明 global 确实有效,而不是外部作用域:

In [2]: def foo():
...: global bar
...: bar = []
...:

In [3]: def oof():
...: bar.append('x')
...:

In [4]: foo()

In [5]: oof()

In [6]: oof()

In [7]: oof()

In [8]: oof()

In [9]: bar
Out[9]: ['x', 'x', 'x', 'x']

无论如何,全局变量是邪恶的!

关于python - 如何在 IPython 中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924918/

24 4 0
文章推荐: python - 使用Flask解决静态路由和动态路由的冲突
文章推荐: python - 具有链接 FK 的 Django 可重用应用程序?
文章推荐: python - lxml 找到 ID 为 ='post-[0-9]*' 的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com