【发布时间】:2017-11-20 02:26:12
【问题描述】:
我正在编写一些代码,但其中一部分有错误。 但是我找不到错误发生的原因。
代码(示例;类似于错误部分):
class Test:
def __init__(self,a=0):
self.x = a
self.l = [2**x for x in range(a)] #<--- self.l = [1,2,4,8,16]
self.base()
def base(self):
expr = "self.l{0} = [self.l[x]+{0} for x in range(self.x)]" #<--- when i=4, self.l4 = [5,6,8,12,20]
for i in range(self.x):
exec(expr.format(i))
w = Test(5)
print(w.l4)
所以我想我明白了:
[5, 6, 8, 12, 20]
但是,
File "D:/Documents and Settings/Desktop/py/py/test2.py", line 12, in <module>
w = Test(5)
File "D:/Documents and Settings/Desktop/py/py/test2.py", line 5, in __init__
self.base()
File "D:/Documents and Settings/Desktop/py/py/test2.py", line 10, in base
exec(expr.format(i))
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>
NameError: name 'self' is not defined
(抱歉英语不好)
【问题讨论】:
-
这能回答你的问题吗? How does exec work with locals?
标签: python exec eval self nameerror