This:
for player in players:
player = Character()
will create a new Character
instance for each item in players
(not using the item itself) and assign it to the player
variable (each time ovverridding the previous assignment). This won't of course change anything to your players
list. After the loop is terminated, you get one single Character()
instance bound to the player
variable, and that's all. IOW, you'd get the same practical result replacing the loop with a single:
player = Character()
but it won't obviously be of any use.
print(red.life)
Where have you defined a variable named red
?
or if i try
print("red".life)
"red"
is a string. A string has no attribute life
.
for some reason it uses player as object for the
class but I want the element of the list to be used!
The "elements of the list" (I assume you mean the players
list) are strings too. If you want to get a list of Character
instances instead, you can get it that what:
class Character(object):
def __init__(self, name):
self.name = name
self.life = 50
playernames = ["red", "green", "blue", "42"]
players = [Character(name) for name in playernames]
but that will still not create any variables named red
, green
etc, just a list of Character instances.
If you want to be able to retrieve specific Character instances, you will either need to explicitly create variables or use a dict. Creating variables:
red = Character("red")
yellow = Character("yellow")
# etc
but this means all your characters are hardcoded - you cannot have more or less players nor name them differently etc.
Using a dict:
playernames = ["red", "green", "blue", "42"]
players = {name:Character(name) for name in playernames}
print(players["red"].life)
print(players["green"].life)
# etc