如何使用python中的循环创建多个类对象? [英] How to create multiple class objects with a loop in python?

查看:1104
本文介绍了如何使用python中的循环创建多个类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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 )分配一个变量,使代码更短?

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


推荐答案

这个问题每天都会出现在某些变体中。答案是:保留您的数据超出您的变量名称,并这是必须的博客帖子

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.

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

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

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

objs[0].do_sth()

这篇关于如何使用python中的循环创建多个类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆