我需要在主程序中创建全局deques,并在从该程序调用的函数中使用它们。在我的例子中,我创建了一个deque“questions”,并向deque添加了两个列表。我从主程序打印deque,以表明它已成功创建并填充。在
在函数中,我试图将deque“questions”中的项弹出到变量“question”中,但得到的却是“NameError:global name‘questions’is not defined”
如何访问函数中的deque?被注释掉的“全局问题”和“从集合导入deque”也得到了相同的结果,所有的排列都包括或排除这些行。在
函数在一个模块中,文件结构如下:
├── problemmain.py
├── modules
│ ├── problemchild.pyc
│ ├── problemchild.py
│ ├── __init__.pyc
│ └── __init__.py
在问题main.py公司名称:
^{pr2}$模块初始化:
#!/usr/bin/python
#__all__ = ["readconf",]
模块/问题儿童.py公司名称:
#!/usr/bin/python
def problem_child():
"""Determine what's wrong with modules scope and deque
"""
# from collections import deque
# global questions
while True:
#question = questions.pop()
question = questions.pop()
print "Question is: "
print question
print "----------------------------------------------------"
输出:
./problemmain.py
deque([['item1', 'item2', 'item3', ['inneritem1', 'inneritem2', 'inneritem3', 'inneritem4', 'inneritem5', 'inneritem6']], ['item1', 'item2', 'item3', ['inneritem1', 'inneritem2', 'inneritem3', 'inneritem4', 'inneritem5', 'inneritem6']]])
Traceback (most recent call last):
File "./problemmain.py", line 17, in <module>
problem_child()
File "/home/justin.h.haynes/rmd/modules/problemchild.py", line 11, in problem_child
question = questions.pop()
NameError: global name 'questions' is not defined
尝试亚伦的建议,并将“问题队列”替换为以下内容:
$ ./problemmain.py
Traceback (most recent call last):
File "./problemmain.py", line 13, in <module>
modules.questions_queue=deque()
NameError: name 'modules' is not defined
为什么不把它放在一个公共命名空间中呢?在
然后像这样访问它:
^{pr2}$编辑
你也需要
或者
我建议您将
questions
作为显式参数:从来电者那里传过来:
^{pr2}$如果您觉得需要使用
global
变量,这通常是一个不好的迹象。在@jornsharpe已经回答了这个问题,但是我认为对为什么这是答案的思考过程进行更多的探讨会有建设性的,而且我认为编辑这个问题是不合适的,因为一个可能尝试做同样事情的用户不会找到原始示例。在
这个问题的实质是“我如何在全球范围内访问一个deque”,但在这里,我将解释当我问到我上面更具体的问题时,我的假设有什么不对。这个问题仍然有效——只是基于错误的假设和理解。在
函数不应该修改全局变量(或者实际上是全局变量)。没有太多好的理由这么做。对于第9.1节中提到的变量、列表和“大多数其他类型”(http://docs.python.org/2/tutorial/classes.html),这是正确的。在
然而,并非所有对象都是如此。当一个人通过一个deque时,只有引用被传递(如果我过于简单化,有人可以纠正我)。我理解这一点的方式是引用同一对象的命名空间中的另一个类似指针的构造。在传递deque的情况下,在函数内部和全局空间中有一个引用。在
所以我可以创建一个deque,添加一些元素,传递给一个函数,将元素添加到我在函数中传递给的deque中,然后在函数外部查看内容并证明我一直在操作同一个对象:
在输出中,我们看到字符串是函数的本地字符串,而在deque中,我们只是对同一个deque实例有一个不同的名称,这个实例在程序的主要部分和函数内部都进行了修改:
一/测试.py在
^{pr2}$相关问题 更多 >
编程相关推荐