Python 全局变量
def say_boo_twice():
global boo
boo = 'Boo!'
print boo, boo
boo = 'boo boo'
say_boo_twice()
输出是
嘘!嘘!
不像我预期的那样。由于我将 boo
声明为全局,为什么输出不是:
嘘嘘嘘嘘
def say_boo_twice():
global boo
boo = 'Boo!'
print boo, boo
boo = 'boo boo'
say_boo_twice()
The output is
Boo! Boo!
Not as I expected. Since I declared boo
as global, why is the output not:
boo boo boo boo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您已在函数内更改了
boo
,为什么它不会更改?另外,全局变量也不好。You've changed
boo
inside your function, why wouldn't it change? Also, global variables are bad.因为你事先就重新分配了。注释掉
boo = 'Boo!'
你就会得到你所描述的内容。另外,
global boo
是不必要的,boo
已经在全局范围内。这就是
global
发挥作用的地方然而:
Because you reassign right before hand. Comment out
boo = 'Boo!'
and you will get what you describe.Also that
global boo
is unnecessary,boo
is already in global scope.This is where the
global
makes a differenceWhereas:
在将 boo 声明为全局之后,您将重新对其进行分配,因此该值是您分配给它的最后一个值。如果删除第三行,您将得到预期的输出。
You are re-assigning boo after you declare it as global, so the value is the last one you assigned to it. If you removed line three, you would get the output you expect.
本质上,您在调用该函数时重新分配 boo 。
检查它如何与 globals() 和 locals() 函数一起使用。
Essentially you reassign boo when you call the function.
Check how this works with the globals() and locals() functions.
在给出示例之前,我希望您了解 python 中全局变量和局部变量之间的区别
全局变量: 这是特定于当前模块的
局部变量: 这是特定于当前函数或我们在 python 中调用它的方法
如果本地变量和当前变量具有相同的名称 boo 会怎样?
在这种情况下,如果您没有在中将变量 boo 定义为全局相同的方法或函数,默认情况下将其用作局部变量
进入您的代码
您已在方法中将 boo 定义为全局say_boo_twice() 。
问题是,当您尝试在该方法中初始化 boo = 'Boo!' 时,您实际上会覆盖之前初始化为 boo = 'boo boo' 的内容
尝试此代码
- - 我还没有在方法 say_boo_twice() 中初始化变量 boo
祝一切顺利! !! !
Before giving an example I want you to understand difference between global and local variable in python
global variable: This is specific to current module
local variable: This is specific to current functions or methods as we call it in python
What if both local and current variable have the same name boo ?
In such case if you don't define your variable boo as global in the same method or function it will by default use it as local variable
Coming to your code
You have defined boo as global in your method say_boo_twice().
The catch is when you try to initialize boo = 'Boo!' in that method you are actually overwriting what you initialized previously as boo = 'boo boo'
Try this code
-- I have not initialized variable boo inside method say_boo_twice()
All the Best !!! !! !
global boo 仅在方法 say_boo_twice 内是全局的,并且已在此方法内重新分配了一个值。您需要了解它可以是全局的词法或范围,或者您想要它是什么。在这种情况下,就在打印之前,它被分配了一个值“Boo!”这就是它正确打印的内容。
global boo is global only inside method say_boo_twice and has been re-assigned a value inside of this method. You need to understand the lexical or scope where it can be global or what you want it to be. In this context, just before printing, it was assigned a value of 'Boo!' and that is what it correctly printed.