Python exec() NameError: name 'self' is not defined

Python exec() NameError: name 'self' is not defined

为什么我得到 NameError: name 'self' is not defined?此代码在 class 中的函数下。 main_root 应该可以在 class 中的任何地方访问,因为它在 __init__ 下被初始化为 self.main_root = an element。函数的第一个参数也是self

root_string = "self.main_root[0][1]"

globals()
code_locals = {'temp_string':""}

command_string = "temp_string = str(" + root_string + ".tag) + str(" + root_string + ".attrib)"
exec(command_string,globals(),code_locals)

如果我设置 root_string = "main_root[0][1]" 那么我将得到 main_root is undefined。即使我尝试事先分配 main_root = copy.deepcopy(self.main_root)

应该是

root_string =self.main_root[0][1]

或者如果你想要它作为字符串,那么就作为

root_string = str(self.root[0][1])

您必须将变量转换为您想要的类型(字符串、整数等)您不能将其初始化为“self.main_root[0][1]”

如果您需要在 exec 语句中访问 self 变量,您应该在示例中使用 locals() 而不是 code_locals 传递第三个参数。