【发布时间】:2016-01-17 18:42:50
【问题描述】:
我正在尝试计算化学方程式中元素的数量。我以某种方式创建的调试器无法访问我程序中的全局变量。具体来说,我正在尝试访问carrots,但left 没有被添加到堆栈中。有什么想法吗?
Debug.py
class Debugger(object):
def __init__(self,objs):
assert type(objs)==list, 'Not a list of strings'
self.objs = objs
def __repr__(self):
return '<class Debugger>'
def show(self):
for o in self.objs:
print o,globals()[o] #EDIT
Chemical_Balancer.py
from Debug import Debugger
def directions():
print 'Welcome to the chem Balancer.'
print 'Use the following example to guide your work:'
global left #LEFT IS GLOBAL
left = 'B^6 + C^2 + B^3 + C^3 + H^9 + O^4 + Na^1'
print left
print "#Please note to use a 'hat' when entering all elements"
print '#use only one letter elements for now'
# left = raw_input('enter formula:') #enter formula to count
directions()
chem_stats = {}
chem_names = []
chem_names = []
chem_indy = []
for c in range(len(left)):
if left[c].isalpha() and left[c].isupper():
chars = ''
if left[c+1].islower():
chars += left[c]+left[c+1]
else:
chars += left[c]
#print chars
chem_indy.append(c)
chem_names.append(chars)
carrots = [x for x in range(len(left)) if left[x]=='^']
debug = Debugger(['carrots','chem_names','chem_indy','chem_stats']) # WITHOUT LEFT
debug.show()
错误信息:
Traceback (most recent call last):
File "C:\Python27\#Files\repair\Chemical_Balancer.py", line 38, in <module>
debug.show()
File "C:\Python27\lib\site-packages\Debug.py", line 12, in show
print o,globals()[o]
File "<string>", line 1, in <module>
KeyError: 'carrots'
【问题讨论】:
-
你为什么使用 eval()? (我不是在问,因为它是错误的,只是想知道为什么要使用它。)
-
找到变量的值。
-
是的,我用 eval() 尝试了一些东西,我想我会找到上面的文档
-
它引发了
KeyError。 -
不要使用全局变量,而是使用字典。
标签: python python-2.7 nameerror global-scope