【问题标题】:NameError: name 'self' is not defined IN EXEC/EVALNameError:名称“self”未在 EXEC/EVAL 中定义
【发布时间】: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

(抱歉英语不好)

【问题讨论】:

标签: python exec eval self nameerror


【解决方案1】:

这里不需要 eval 或 exec。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2022-06-13
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多