NameError:名称'self'未在EXEC / EVAL中定义

时间:2017-06-17 11:21:30

标签: python exec eval self nameerror

我正在编写某些内容,并且在一个部分中存在错误。 但我无法找到错误发生的原因。

代码(示例;类似于错误部分):

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

(抱歉英语不好)

1 个答案:

答案 0 :(得分:-1)

这里不需要eval或exec。

for i in range(self.x):
    setattr(self, "l{}".format(i), [self.l[x]+i for x in range(self.x)])

虽然我不知道你为什么要这样做;最好将其保留为列表而不是动态设置属性。