是否使用exec进行pythonic变量赋值?

问题描述 投票:1回答:1

考虑此代码:

self._t10_test = None
self._t20_test = None
self._t30_test = None

id_lst = ['10', '20', '30']
msg_lst = ['Message for A', 'Message for B', 'Message for C')

在这种情况下使用exec是否正确?

for id, msg in zip(id_lst, msg_lst):
    exec((f'self._t{id}_test = {msg}')

或者这会更pythonic吗?

for id, msg in zip(id_lst, msg_lst):
    set_msg(id, msg)


def set_msg(id, msg):
    if id == '10':
        self._t10_test = msg
    elif id == '20':
        self._t20_test = msg
    elif id == '30':
        self._t30_test = msg
python python-3.x list design-patterns exec
1个回答
2
投票

exec()的使用总是一个坏主意。我发现一般来说,如果您认为需要在变量名中使用变量,那么更好的选择是使用字典。例如:

© www.soinside.com 2019 - 2024. All rights reserved.