我有一个名为Square的课程。我正在尝试将字符串转换为变量,并为每个变量分配相同的类。
a = 'var'
exec("%s = %d" % (a,Square()))
上面的示例代码不起作用,因为错误说使用整数而不是Square:
TypeError: %d format: a number is required, not Square
%d必须更改为什么才能使其正常工作?
答案 0 :(得分:1)
使用字典效果很好
x = {}
a = 'var'
x[a]= Square()
答案 1 :(得分:0)
您尝试为Square
占位符添加int
个对象。
但是在你的问题中,你说你要分配一个动态变量。
试试这个
var_name = "a"
exec("%s = Square()" % var_name)
您希望exec
创建Square
对象。
注意"动态变量"可能不是你想要的。你将在获得变量值方面遇到同样的困难。
看一下dict
课程。有了它,您可以非常容易地存储由键表示的对象。
例如
# create a dictionary
my_squares = {}
# create the square and put it into the dict
my_squares["some name"] = Square()
# do whatever you want with your square
print(my_squares["some name"])