I have a question, my problem is that i want to create x amount of instances of a class and store(inside the instance) the order they were created in. Is there a way that i can do that because i tried but could not do anything and im new to python i just started programming, and this is my first language so please be tolerant.
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)
But for some reason this doesn't work, i dont know why, please clarify the problem if you know it.
CodePudding user response:
The class itself can give ids to its instances.
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
CodePudding user response:
Using list comprehension as described in the comments is not a bad way to go but I'll put this here just to give you a introduction to lists.
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))
The only wierd thing here is that because lists are 0 indexed ants[0].id
will be 1 and ant[99].id
will be 100. If you do ants = [Ant(i) for i in range(MaxAnts)]
you will have your index lined up with your ids, ants[7].id = 7
. But you could get the same effect by putting i =1
after ants.append(Ant(i))
instead of the line before.
CodePudding user response:
To create x amount of instances of some class you would need to use some form of iteration and append them to a collection that you would be able to access.
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
Since by default 'range' gives you a range from 0 to argument - 1, in case you want to start your order from 1, you should start your iteration from 1, and end it on MaxAnts:
for i in range(1, MaxAnts 1): # Iterating i from 1 to MaxAnts
More on lists: https://docs.python.org/3/tutorial/datastructures.html
More on range: https://docs.python.org/3/library/functions.html#func-range