Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterating Variables...?
#3
(May-15-2019, 05:58 AM)JesseTheNewb Wrote: I would like the instance to be "soldier02" the second time I run the function, then "soldier03," etc.
No, you don't want to go this way. It's anti pattern. You should create multiple instances (soldiers) and store each of these instances in a data structure like list.

very basic example

import random

class Soldier:
    def __init__(self, strength):
        self.strength = strength
    
    def __str__(self):
        return (f'Soldier with strength {self.strength}')

my_army = []
for soldier in range(10):
    my_army.append(Soldier(strength=random.randint(5, 10)))

# print all soldiers in the army    
for soldier in my_army:
    print(soldier)

print()
print(my_army[3]) # print again 4th Soldier
Output:
Soldier with strength 8 Soldier with strength 7 Soldier with strength 5 Soldier with strength 6 Soldier with strength 5 Soldier with strength 10 Soldier with strength 10 Soldier with strength 8 Soldier with strength 5 Soldier with strength 9 Soldier with strength 6 >>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Iterating Variables...? - by JesseTheNewb - May-15-2019, 05:58 AM
RE: Iterating Variables...? - by Larz60+ - May-15-2019, 06:05 AM
RE: Iterating Variables...? - by buran - May-15-2019, 06:13 AM
RE: Iterating Variables...? - by JesseTheNewb - May-15-2019, 06:50 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020