考虑以下 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/