如何在python中使用循环创建多个类对象?

时间:2014-02-06 09:34:47

标签: python class object

假设您必须在python中创建10个类对象,并使用它们执行某些操作,例如:

obj_1 = MyClass()
other_object.add(obj_1)
obj_2 = MyClass()
other_object.add(obj_2)
.
.
.
obj_10 = MyClass()
other_object.add(obj_10)

如何使用循环执行此操作,并为每个对象(如obj_1)分配变量,以便代码更短?每个对象都应该可以在循环外部访问

obj_1.do_sth()

5 个答案:

答案 0 :(得分:23)

每天都会在某些变化中询问此问题。答案是:将数据保存在变量名称之外,并this is the obligatory blog post

在这种情况下,为什么不列出objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

答案 1 :(得分:9)

您可以使用列表来定义它。

objs = list()
for i in range(10):
    objs.append(MyClass())

答案 2 :(得分:4)

如上所述创建字典,但在这种情况下,每个键都有您要创建的对象名称。然后将该值设置为要实例化的类,请参阅:

class MyClass:
   def __init__(self, name):
       self.name = name
       self.checkme = 'awesome {}'.format(self.name)
...

instanceNames = ['red', 'green', 'blue']

# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}

然后你只需拨打持有人密钥,即可获得班级的所有属性和方法。

holder['red'].checkme

输出:

'awesome red'

答案 3 :(得分:1)

我希望这就是你要找的东西。

class Try:
    def do_somthing(self):
        print 'Hello'

if __name__ == '__main__':
    obj_list = []
    for obj in range(10):
        obj = Try()
        obj_list.append(obj)

    obj_list[0].do_somthing()

输出:

Hello

答案 4 :(得分:0)

使用不带名称列表的唯一名称字典:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

输出:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."