2017-06-17 100 views
1

我在编码,并且在一部分中出现错误。 但我无法找到错误发生的原因。NameError:名称'self'未定义IN EXEC/EVAL

代码(样本;类似的错误部分):

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

有没有必要在这里评估或执行。

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

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