簡體   English   中英

在 Python 中創建 class 的多個實例

[英]creating multiple instances of a class in Python

所以假設有一個 class A

我可以創建 class A 的實例如下

inst1 = A()

inst2 = A()

inst3 = A()
...

我可以更整潔地完成這項工作嗎?

我必須創建與服務器給出的一定數量一樣多的實例(數量每次都可能不同)。

我期待做類似的事情

for NUM in range(2):
    inst + NUM = A()

那么我想要獲得的實例將是三個實例(inst0、inst1、inst2),它們是 class A。

先感謝您

如果您不為它們分配指定的名稱,則無法創建單個變量,用於創建未知數量的變量使用列表(索引)或字典(命名):

列表

使用 for 循環:

instances = []

for x in range('number of instances'):

    instances.append(A())

使用列表理解(推薦):

instances = [A() for x in range('number of instances')]

字典

使用 for 循環:

instances = {}

for x in range('number of instances'):

    instances['inst' + str(x)] = A()

使用 dict 理解(推薦):

instances = {'inst' + str(x): A() for x in range('number of instances')}

使用字典或列表創建變量

字典

d={}
for x in range(1, 10):
    d[f"inst{x}"] = A()

列表

inst=[]
for i in range(10):
    inst.append(A())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM