Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对使用matplotlib——axis对象的变量范围感到困惑_Python_Matplotlib - Fatal编程技术网

Python 对使用matplotlib——axis对象的变量范围感到困惑

Python 对使用matplotlib——axis对象的变量范围感到困惑,python,matplotlib,Python,Matplotlib,我不知道为什么下面的代码可以工作。如果我将ax分配注释掉,它将停止工作。ax是如何进入函数范围的?这是python版本2.7.2 经过进一步研究,我发现在同一个代码模块中定义的函数可以看到main块中的所有变量。我不知道python是这样工作的!main块中的每个变量对同一源文件中的所有函数都可见。我觉得这并不可取!它似乎违反了函数的功能。我想这个例外是针对main代码块的,但我不会猜到 如何防止此代码模块中定义的函数看到main块中的所有变量 import pylab as plt def

我不知道为什么下面的代码可以工作。如果我将ax分配注释掉,它将停止工作。ax是如何进入函数范围的?这是python版本2.7.2

经过进一步研究,我发现在同一个代码模块中定义的函数可以看到main块中的所有变量。我不知道python是这样工作的!main块中的每个变量对同一源文件中的所有函数都可见。我觉得这并不可取!它似乎违反了函数的功能。我想这个例外是针对main代码块的,但我不会猜到

如何防止此代码模块中定义的函数看到main块中的所有变量

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()

不需要,因为python中的函数总是可以访问全局名称空间,这是它们模块的名称空间

您可以使用模块来隔离函数

只需在模块中定义您的函数,即像
mymod.py
这样的文件。它将只能访问其模块范围。然后您可以在
myscript.py
as中使用它

#file myscript.py
from mymod import myfunction
#and now the function myfunction will not 'see' the variables defined in myscript.py
“我觉得这并不可取!它似乎违背了函数的含义。”

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

你能做的是(通常认为这更好):


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

?在
f
内部,解释器查找符号
ax
。如果找不到它,它会在全局范围中查找它,在全局范围中确实定义了
ax
。您应该修改函数,将
对象作为参数。为什么这样会更好?除了局部变量的微小性能改进,这是一个弱点。您不关心这样的脚本中的名称空间污染,我想说的是,在这种情况下,最好不要使用
if\uuuu name\uuuu
子句,而只编写代码。@GiulioGhirardo您喜欢(重新)将脚本用作模块。也许
main()
是您可能希望从另一个脚本调用的函数,而不是。想象一下,将该脚本扩展为一个模块(但也作为一个独立脚本),并编写另一个(包装器)脚本,该脚本采用命令行选项解析等功能;后一个脚本可以导入该脚本,并执行main(可能使用相同的关键字参数)。
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()