Python-创建多个对象的巧妙方法? [英] Python - neat way of creating multiple objects?
问题描述
我对Python还是很陌生,我对创建具有不同属性的多个对象的巧妙方法有疑问.目前,我必须像这样专门创建每个人:
I'm fairly new to Python and I have a question about a neat way of creating multiple objects with different properties. At the moment I am having to specifically create each one like this:
object1 = MyClass(property=foo,property2=bar)
object1.DoStuff(variable = foobar)
object2 = MyClass(property=foo,property2=bar2)
object2.DoStuff(variable = foobar)
object3 = MyClass(property=foo,property2=bar3)
object3.DoStuff(variable = foobar)
我的问题是我想以这种方式创建许多对象,并且不得不像这样手动创建每个对象,这似乎是非常糟糕的编程.有没有更好的方法来创建多个属性稍有不同的对象?
My problem is that I want to create dozens of objects in this way and having to manually create each one like this seems like very bad programming. Is there a better way to create multiple objects with slightly different properties?
我想我想要要做的事情是这样的:
I guess what I want to do is something like:
list = [prop1, prop2, prop3, prop4, prop5]
while i < len(list)
object_i = MyClass(property=foo,property2=list[i])
object_i.DoStuff(variable = foobar)
i+=1
并创建5个名为object_1,object_2等的对象
And have this create 5 objects named object_1, object_2, etc etc
这可能吗?
推荐答案
如果您有名称为object_1
,object_2
等的对象,并且希望对所有这些对象执行通用操作,则这清楚地表明您实际上应该使用列表objects
,并使用循环执行常见操作.
If you have objects with the names object_1
, object_2
etc. and want to perform common operations on all these objects, this is a clear sign that you should actually be using a list objects
, and use loops to perform the common operations.
props = <some list here>
objects = [MyClass(property=foo, property2=prop) for prop in props]
for obj in objects:
obj.do_stuff(variable=foobar)
这篇关于Python-创建多个对象的巧妙方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!