python - 默认情况下 Python 变量是全局变量吗?

标签 python c++ python-3.x

考虑以下 python 代码:

a = 10
def fun():
    print(a)
fun()

这在 ipython notebook 中运行良好,输出为 10

在 C++ 中考虑这段代码:

#include <iostream>

void fun()  {
    std::cout << a << std::endl;
}

int main()  {
    int a = 10;
    fun();
    return 0;
}

编译时报错:

compare-fun.cpp: In function ‘void fun()’:
compare-fun.cpp:4:18: error: ‘a’ was not declared in this scope
     std::cout << a << std::endl;

我对python代码感到困惑,为什么即使在fun中没有定义a,它也能调用a

最佳答案

与您的 C++ 代码等效的 Python 代码实际上如下所示:

def fun():
    print(a)

def main():
    a = 10
    fun()

if __name__ == '__main__':
    main()

这在运行时会产生以下内容:

Traceback (most recent call last):
  File "test1.py", line 9, in <module>
    main()
  File "test1.py", line 6, in main
    fun()
  File "test1.py", line 2, in fun
    print(a)
NameError: global name 'a' is not defined

与您的 Python 代码等效的 C++ 代码是这样的:

#include <iostream>

int a = 10;

void fun()  {
    std::cout << a << std::endl;
}

int main()  {
    fun();
    return 0;
}

这在运行时输出 10

关于python - 默认情况下 Python 变量是全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189541/

相关文章:

python - Python 中默认参数的范围

c++ - 避免输出到 CppUnit 的点

C++ 初学者 : using namespace error

c++ - 使用 Borland C++ 版本 5 的优点

python - ArgumentParser.add_argument : How to use action parameter with custom type parameter?

python-3.x - 创建数据类时,我可以使用类型模块中的 Union 和 Optional 类型吗?

python - 有没有办法在 Python 中编辑包含图像的 xlsx 工作簿?

python - 错误: 'value' : keys_to_typing(value)} while sending keys selenium python

使用单独(顺序)Python 进程的 Python Nose 单元测试

python - 从 GPS 点绘制线