我想創建一個類的x數量的實體并存盤(在實體內)它們的創建順序。有沒有辦法可以做到這一點?
MaxAnts = 100
class Ant:
def __init__(self,id):
self.id = id
# then I will use the id to do math
i = 0
if i <= MaxAnts:
i = 1
i = Ant(i)
但由于某種原因,這不起作用。
uj5u.com熱心網友回復:
類本身可以為其實體提供 id。
class Ant:
counter = 0 # counter is a class variable
def __init__(self):
cls = type(self)
self.id = cls.counter # id is an instance variable
cls.counter = 1
# example:
a = Ant()
b = Ant()
c = Ant()
print(a.id, b.id, c.id) # prints: 0 1 2
uj5u.com熱心網友回復:
使用評論中描述的串列理解并不是一個壞方法,但我將其放在這里只是為了向您介紹串列。
MaxAnts = 100
class Ant:
def __init__(self,id):
self.id = id
#then i will use the id to do math
ants = [] # or ants = list() , same thing
i = 0
if i <= MaxAnts:
i = 1
ants.append(Ant(i))
這里唯一奇怪的是,因為串列是 0,所以索引ants[0].id將是 1 并且ant[99].id將是 100。如果你這樣做ants = [Ant(i) for i in range(MaxAnts)],你的索引將與你的 id 對齊,ants[7].id = 7. i =1但是你可以通過在之后ants.append(Ant(i))而不是之前的行來獲得相同的效果。
uj5u.com熱心網友回復:
要創建某個類的 x 數量的實體,您需要使用某種形式的迭代并將它們附加到您可以訪問的集合中。
MaxAnts = 100
class Ant:
def __init__(self,id):
self.id = id
#then i will use the id to do math
ants = [] # A list to store your ants
for i in range(MaxAnts): # Iterating i from 0 to MaxAnts - 1
ant = Ant(i) # Creating your new ant with the i as a parameter
ants.append(ant) # Adding your new ant to the ants list
因為默認情況下“范圍”為您提供從 0 到引數 - 1 的范圍,如果您想從 1 開始您的訂單,您應該從 1 開始迭代,并在 MaxAnts 上結束:
for i in range(1, MaxAnts 1): # Iterating i from 1 to MaxAnts
有關串列的更多資訊:https ://docs.python.org/3/tutorial/datastructures.html
更多關于范圍:https ://docs.python.org/3/library/functions.html#func-range
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430555.html
上一篇:表視圖單元格沒有初始化器
