所以,我想从我循环的列表列表中实际创建类实例。怎么做?
class foo:
def __init__(self, first, second):
self.first = first
self.second = second
my_list = [[a_0, a_1, a_2], [b_0, b_1, b_2], [c_0, c_1, c_2]]
i = 1
instance_name = instance_
for list in my_list:
x = instance_name + str(i)
x = foo(list[0], list[2])
i += 1
我知道循环中的第二个x是完全错误的。但是我需要能够使用x的值来调用我的实例。有什么帮助吗?
答案 0 :(得分:1)
正如@roganjosh的评论说变量x
的数据被覆盖了,所以如果你想创建变量使用locals()
,但这不是一个好习惯。你最好去字典存储实例,即
class foo:
def __init__(self, first, second):
self.first = first
self.second = second
a_0,a_1,a_2 = 1,2,3
b_0,b_1,b_2 = 4,5,6
c_0,c_1,c_2 = 7,8,9
my_list = [[a_0, a_1, a_2], [b_0, b_1, b_2], [c_0, c_1, c_2]]
for i,li in enumerate(my_list):
locals()['instance_{}'.format(i+1)] = foo(li[0], li[2])
# instance_1.first
# 1
# instance_3.first
# 7
字典方法是:
x = {'instance_{}'.format(i+1): foo(li[0], li[2]) for i,li in enumerate(my_list) }
#x['instance_1'].first
#1
答案 1 :(得分:0)
只需使用列表理解并构建该列表中的实例:
class Foo:
def __init__(self, first, second):
self.first = first
self.second = second
# List of parameters to pass to Foo
args_list = [(1, 2), (3, 4), (5, 6)]
# Add an instance of Foo(first num, second num) to the instances list
# for every set of arguments above
instances = [Foo(value[0], value[1]) for value in args_list]
# Print out each of the instances values
for instance in instances:
print(instance.first, instance.second)
# prints:
# 1 2
# 3 4
# 5 6
# OR you can call an individual instance like so
print(instances[0].first, instances[0].second)
# prints:
# 1 2