Is there a way of formating a variable?
For examp开发者_如何学编程le, I'd like to automate the creation of a variable named M_color, where M is a string of value "bingo". The final result would be bingo_color. What should I do if the value of M changes during the execution?
The best solution for this kind of problem is to use dictionaries:
color_of = {}
M = "bingo"
color_of[M] = "red"
print(color_of[M])
If the 'variable' can be an attribute of an object, you could use setattr()
class Color(object):
pass
color = Color()
attr_name = '{foo}_color'.format(foo='bingo')
setattr(color, attr_name, 'red')
Beyond that, you're looking at using eval()
精彩评论