我有 C、C++ 和 Java 背景。所以我很好奇为什么下面的 Python 代码可以工作:
def f1():
print(xy)
if __name__ == "__main__":
print("Hello")
xy = 34
f1()
它打印:
Hello
34
如何访问函数f1
中的xy
? xy
未在 f1
内部定义,xy
是在 if __name__ == "__main__"
的条件 block 中定义的>?
最佳答案
Global Variables
In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
关于python - 为什么我可以访问 Python 函数外部有条件定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973766/