在 Python 3 中对对象进行 exec 调用时出现语法错误

Syntax error with exec call to an object in Python 3

提问人:mag non 提问时间:1/25/2023 更新时间:1/25/2023 访问量:37

问:

我真的不明白是什么原因导致了这个问题,有人可以帮我指出来吗?

with shelve.open(obj_path) as obj:
    for as_num in obj['as_number_list']:  # ignore warning, obj['as_number_list'] is a list
        temp = charge_as(obj['as_' + str(as_num)])  # temp is an object
        as_test = temp  # doing like this is ok
        print(type(as_test))
        exec("as_{}_obj = {}".format(as_num, temp))  # **error here**

它给出了这样的语法错误:

<class 'instruments.AS'>
Traceback (most recent call last):
  File "...", line 45, in <module>
    exec("as_{}_obj = {}".format(as_num, temp))
  File "<string>", line 1
    as_1_obj = <instruments.AS object at 0x000002A86732E290>
               ^
SyntaxError: invalid syntax

我试过了

exec("as_{}_obj = {}".format(as_num, temp.__dict__))

未显示任何错误,但现在 as_{}_obj 属于类“dict”而不是类“instruments”。AS'

python-3.x 对象 语法错误

评论

1赞 SuperStormer 1/25/2023
这回答了你的问题吗?如何创建变量变量?

答:

0赞 mag non 1/25/2023 #1

第 45 行: exec(“as_{}_obj = temp”.format(as_num))