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

查看:58
本文介绍了如何在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.

在这种情况下,为什么不制作一个 obj 列表?

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天全站免登陆