帮助定义全局名称
我的代码:
def A():
a = 'A'
print a
return
def B():
print a + ' in B'
return
当 B() 输入解释器时,我得到
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 Define a?当 B() 输入解释器
编辑时,我希望最终结果是“A in B”: 如果可能的话,我想将 a 的定义保留在 A() 内。
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
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
edit:
I'd like to keep the definition of a within A() if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
打印:
顺便说一句:你永远不需要在函数末尾有一个简单的“返回”。
this prints:
BTW: You never need a plain "return" at the end of a function.
我对 Python 还很陌生,您可能想对以下内容持保留态度,但是您是否考虑过将变量 a 以及函数 A() 和 B() 作为类的成员?
当我将上面的代码保存在文件中并运行它时,它似乎按预期工作。
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?
When i save the code above in a file and run it, it seems to work as expected.
您可以使用
global
关键字来做到这一点:但是,使用全局变量通常是一个坏主意 - 您确定没有更好的方法来完成您想做的事情吗?
You can do this by using the
global
keyword: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?
查看我的回答这个问题。基本上:
创建一个仅包含全局数据的新模块(在您的情况下,假设
myGlobals.py
):然后您想要访问此数据的每个文件都可以以这种方式执行此操作:
所以在您的案件:
check out my answer from this SO question. Basically:
Create a new module containing only global data (in your case let's say
myGlobals.py
):and then each file you want to have access to this data can do so in this fashion:
so in your case:
只需像这样输入,无需创建函数或类:
Just type like this, no need to create fuction or class :