函数内的 globals() 作用域

globals() scope inside a function

我对 python

中的 globals() 有疑问

我的示例代码

b=9
def a1():
 'kkk'

a1()
print globals()

我得到了全局输出 b

因为 b 是全局的,我希望我可以在任何地方修改它 所以我将代码修改为

b=9
def a1():
 'kkk'
 b=100
a1()
print globals()

仍然我的 globals() 说 b 是 100。为什么函数内的 b 被当作本地值,而我的 globals() 说它是全局的?

注意:如果我在函数中添加关键字 global b,它会转换为全局。 我的问题是为什么在 globals() 将 b 声明为全局时 b 在函数内部没有被修改?

在函数内部,除非使用关键字global,否则修饰的不是全局变量。相反,创建一个局部变量并在它超出范围后立即销毁

参考Python docs了解更多信息。复制文本以防 URL 不起作用

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

由于你的代码b是a1()中的局部变量,要使用全局变量,你应该先对python说,然后再使用,如下:

b=9
def a1():
 'kkk'
 global b
 b=100

a1()
print globals()