简体   繁体   English

使用Python代码制作多个实例

[英]Python code to make multiple instances

Is there a way to make multiple instances of a class in python without having to type out the name for each instance? 有没有一种方法可以在python中制作一个类的多个实例,而不必为每个实例键入名称? something like. 就像是。

for i in range(10):
    i = some_class()

Is this possible? 这可能吗? or am i just a huge noob. 还是我只是一个巨大的菜鸟。

Yes. 是。 You just need a list to store your objects. 您只需要一个列表来存储您的对象。

my_objects = []
for i in range(10):
    my_objects.append(some_class())

Use a dictionary: 使用字典:

d= {}

for i in range(10):
    d[i] = SomeClass()

If you just want to store a list of instances, use a list comprehension: 如果只想存储实例列表,请使用列表推导:

instances = [SomeClass() for _ in range(10)]

A list: 一个列表:

In [34]: class SomeClass():
        pass
   ....: 

In [35]: instances = [SomeClass() for _ in range(5)]

In [36]: instances
Out[36]: Out[41]: 
[<__main__.SomeClass at 0x7f559dcea0f0>,
 <__main__.SomeClass at 0x7f559dcea2e8>,
 <__main__.SomeClass at 0x7f559dcea1d0>,
 <__main__.SomeClass at 0x7f559dcea208>,
 <__main__.SomeClass at 0x7f559dcea080>])]

A dict where each i is the key and an instance is the value: 一个字典,其中每个i是键,一个实例是值:

In [42]: d= {}

In [43]: for i in range(5):
   ....:         d[i] = SomeClass()
   ....:     

In [44]: d
Out[44]: 
{0: <__main__.SomeClass at 0x7f559d7618d0>,
 1: <__main__.SomeClass at 0x7f559d7617f0>,
 2: <__main__.SomeClass at 0x7f559d761eb8>,
 3: <__main__.SomeClass at 0x7f559d761e48>,
 4: <__main__.SomeClass at 0x7f559d7619e8>}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM