Python 帮助定义全局名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3595690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Help Defining Global Names
提问by rectangletangle
My Code:
我的代码:
def A():
a = 'A'
print a
return
def B():
print a + ' in B'
return
When B() is entered into the interpeter I get
当 B() 进入 interpeter 时,我得到
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<module1>", line 9, in B
NameError: global name 'a' is not defined
How should I go about defining a? I want the end result to be 'A in B', when B() is entered into the interpreter
我应该如何定义一个?当 B() 进入解释器时,我希望最终结果是“A in B”
edit: I'd like to keep the definition of a within A() if possible.
编辑:如果可能,我想在 A() 中保留 a 的定义。
采纳答案by Klaus-Dieter Warzecha
i'm pretty new to Python and you might want to take thes following with a grain of salt, but did you consider to have your variable a and the functions A() and B() as members of a class?
我对 Python 很陌生,您可能想对以下内容持保留态度,但是您是否考虑过将变量 a 以及函数 A() 和 B() 作为类的成员?
class myClass(object):
def __init__(self):
self.a = ''
def A(self):
self.a = 'A'
print self.a
def B(self):
print self.a + ' in B'
def main():
stuff = myClass()
stuff.A()
stuff.B()
if __name__ == '__main__':
main()
When i save the code above in a file and run it, it seems to work as expected.
当我将上面的代码保存在一个文件中并运行它时,它似乎按预期工作。
回答by Ned Batchelder
def A():
global a
a = 'A'
print a
def B():
global a
print a + ' in B'
A()
B()
this prints:
这打印:
A
A in B
BTW: You never need a plain "return" at the end of a function.
顺便说一句:在函数的末尾你永远不需要简单的“返回”。
回答by Matt Joiner
a = 'A'
def B():
print a + ' in B'
回答by Amber
You can do this by using the globalkeyword:
您可以通过使用global关键字来做到这一点:
def A():
global a
a = 'A'
def B():
global a
# ...
However, using global variables is generally a bad idea- are you sure there's not a better way to do what you want to do?
然而,使用全局变量通常是一个坏主意——你确定没有更好的方法来做你想做的事吗?
回答by dls
check out my answer from this SO question. Basically:
从这个 SO 问题中查看我的答案。基本上:
Create a new module containing only global data (in your case let's say myGlobals.py):
创建一个仅包含全局数据的新模块(在您的情况下,假设myGlobals.py):
# create an instance of some data you want to share across modules
a=0
and then each file you want to have access to this data can do so in this fashion:
然后您想要访问此数据的每个文件都可以以这种方式访问:
import myGlobals
myGlobals.a = 'something'
so in your case:
所以在你的情况下:
import myGlobals
def A():
myGlobals.a = 'A'
print myGlobals.a
def B():
print myGlobals.a + ' in B'
回答by user4927296
Just type like this, no need to create fuction or class :
只需像这样输入,无需创建功能或类:
global a
a = 'A'
print a
print a + ' in B'

