gpt4 book ai didi

python - 对使用 matplotlib 的变量范围感到困惑——轴对象

转载 作者:行者123 更新时间:2023-12-01 05:00:35 24 4
gpt4 key购买 nike

我不知道为什么下面的代码有效。如果我注释掉 main 中的 ax 分配,它就会停止工作。 ax 如何进入函数范围?这是Python版本2.7.2。

经过更多研究,我发现在同一代码模块中定义的函数可以看到 ma​​in block 中的所有变量。我不知道 python 是这样工作的! ma​​in block 中的每个变量对于同一源文件中的所有函数都是可见的。这对我来说并不理想!这似乎违反了函数的含义。我想这个异常(exception)是针对 ma​​in 代码块的,但我不会猜到它。

如何防止此代码模块中定义的函数看到 ma​​in block 中的所有变量?

import pylab as plt

def f():
ax.plot([1],[2]) # How is this ever defined?
return

if (__name__ == "__main__"):
fig = plt.figure()
plt.clf()
ax = plt.subplot(111,polar=True) # If I comment this out, then ax is not defined error in function call
plt.hold(True)
f()

最佳答案

“这对我来说并不理想!它似乎违反了函数的含义。”

然后您应该避免在代码中使用全局变量。请注意,您所指的主要 block 是(该模块/脚本的)全局命名空间。有一个 if 语句,但这并不意味着“主” block 突然成为一个特殊函数。

你可以这样做(无论如何,这通常被认为更好):

import pylab as plt

def f():
ax.plot([1],[2]) # This is now never defined
return

def main():
fig = plt.figure()
plt.clf()
ax = plt.subplot(111,polar=True) # ax is now local to the main() function only.
plt.hold(True)
f()

if __name__ == "__main__": # No parentheses for an if-statement; very un-Pythonic
main()

现在,这每次都会导致错误,因为 ax 仅在 main() 内定义,而不是在全局(模块)命名空间中定义。

关于python - 对使用 matplotlib 的变量范围感到困惑——轴对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26295482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com