如果在python中使用eval,如何使用eval

yeh*_*ahs 0 python

我有一个全局变量1,2,3 ......我有一个变量"num"(它是一个字符串)可以是"一个"或"两个"或"三个"......我想做下一个事情:

if num == "one":
   one = True
elif num=="two":
   two = True
elif num=="three":
   three = True
...
Run Code Online (Sandbox Code Playgroud)

在Perl中,我可以用1行来完成:类似于eval"$ num = True"而不是上面的long if.我怎么能在python中做到这一点?

Mar*_*ers 8

您可以使用globals()以字典的形式访问全局名称:

globals()[num] = True
Run Code Online (Sandbox Code Playgroud)

但是您通常希望将数据保留在变量名称之外.在这里使用字典而不是全局字符:

numbers = {'one': False, 'two': False, 'three': False}

numbers[num] = True
Run Code Online (Sandbox Code Playgroud)

或者也许是一个对象:

class Numbers:
    one = two = three = False

numbers = Numbers()

setattr(numbers, num, True)
Run Code Online (Sandbox Code Playgroud)