带有导入的全局变量 [英] Global variable with imports

查看:91
本文介绍了带有导入的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

myGlobal = "hello"

def changeGlobal():
   myGlobal="bye"

second.py

from first import *

changeGlobal()
print myGlobal

我得到的输出是

你好

尽管我认为应该是

再见

为什么在调用changeGlobal()函数后全局变量myGlobal没有更改?

Why doesn't the global variable myGlobal changes after the call to the changeGlobal() function?

推荐答案

尝试:

def changeGlobal():
    global myGlobal
    myGlobal = "bye"

实际上,这也不起作用. import *时,您将创建一个新的 local 模块全局myGlobal,该模块不受您想要的更改的影响(只要不对变量进行突变,请参见下文).您可以改用以下方法:

Actually, that doesn't work either. When you import *, you create a new local module global myGlobal that is immune to the change you intend (as long as you're not mutating the variable, see below). You can use this instead:

import nice

nice.changeGlobal()
print nice.myGlobal

或者:

myGlobal = "hello"

def changeGlobal():
   global myGlobal
   myGlobal="bye"

changeGlobal()

但是,如果您的全局变量是可变容器,那么您现在持有对可变变量的引用,并且能够看到对其所做的更改:

However, if your global is a mutable container, you're now holding a reference to a mutable and are able to see changes done to it:

myGlobal = ["hello"]

def changeGlobal():
    myGlobal[0] = "bye"

这篇关于带有导入的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆