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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21598872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:14:24  来源:igfitidea点击:

How to create multiple class objects with a loop in python?

pythonclassobject

提问by alwbtc

Suppose you have to create 10 class objects in python, and do something with them, like:

假设你必须在 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)

How would you do it with a loop, and assign a variable to each object (like obj_1), so that the code will be shorter? Each object should be accessible outside the loop

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

obj_1.do_sth()

采纳答案by RemcoGerlich

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

这个问题每天都会以不同的形式被问到。答案是:不要让你的数据出现在你的变量名之外,这是必读的博文

In this case, why not make a list of objs?

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

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

objs[0].do_sth()

回答by Bardia Heydari

you can use list to define it.

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

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

回答by Tanveer Alam

I hope this is what you are looking for.

我希望这就是你正在寻找的。

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()

Output:

输出:

Hello

回答by Jobel

Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:

正如它所提到的那样创建字典,但在这种情况下,每个键都有您要创建的对象名称的名称。然后将该值设置为要实例化的类,例如参见:

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}

Then you just call the holder key and you will have all the properties and methods of your class available for you.

然后您只需调用持有者键,您就可以使用您的类的所有属性和方法。

holder['red'].checkme

output:

输出:

'awesome red'

回答by vaponteblizzard

Using a dictionary for unique names without a name list:

使用字典获取没有名称列表的唯一名称:

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))

Output:

输出:

"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."

Notice this has O(n) time complexity rather than O(n^2).

请注意,这具有 O(n) 时间复杂度而不是 O(n^2)。