Instead of printing the player variables from the list it prints:
[<__main__.Player object at 0x7f95614f4ee0>, <__main__.Player object at 0x7f95614f4f70>,
<__main__.Player object at 0x7f9561520400>]
Code:
class Player:
def __init__(self, name, swaps, points):
self.player_name = name
self.player_swaps = swaps
self.player_points = points
def add_player(players):
name = input('Enter the new players Name : ')
swaps = 3
points = 0
players.append(Player(name, swaps, points))
print('Player Added \n')
def playerselector():
'''Input for players to choose how many players they want.
Will tell them if not sensible and get them to do it again.
'''
valid = False
while valid is False:
try:
num_players = int(input("How many players do you want? (2-5)\n"))
if num_players >= 2 and num_players <= 5:
valid = True
else:
print("Please choose a number between 2 and 5")
except ValueError:
print("Sorry that isn't a number")
return num_players
num_players = playerselector()
players=[]
for x in range(num_players):
add_player(players)
print(players)
Any tips/solutions?
CodePudding user response:
This should work:
class Player:
def __init__(self, name, swaps, points):
self.player_name = name
self.player_swaps = swaps
self.player_points = points
def __repr__(self):
rep = f'Player({self.player_name}, {self.player_swaps}, {self.player_points})'
return rep
def add_player(players):
name = input('Enter the new players Name : ')
swaps = 3
points = 0
players.append(Player(name, swaps, points))
print('Player Added \n')
def playerselector():
valid = False
while valid is False:
try:
num_players = int(input("How many players do you want? (2-5)\n"))
if num_players >= 2 and num_players <= 5:
valid = True
else:
print("Please choose a number between 2 and 5")
except ValueError:
print("Sorry that isn't a number")
return num_players
num_players = playerselector()
players=[]
for x in range(num_players):
add_player(players)
print(players)
Output:
How many players do you want? (2-5)
3
Enter the new players Name : bob
Player Added
Enter the new players Name : joe
Player Added
Enter the new players Name : tom
Player Added
[Player(bob, 3, 0), Player(joe, 3, 0), Player(tom, 3, 0)]
You can change the rep
variable in the __repr__
method to modify the output.
CodePudding user response:
Add player_return function in class:
def player_return(self):
return [self.player_name,self.player_swaps, self.player_points]
and call it in add_player()
A=Player(name, swaps, points)
players.append(A.player_return())
Ouput
How many players do you want? (2-5)
2
Enter the new players Name : tim
[['tim', 3, 0]]
Player Added
Enter the new players Name : Jerry
[['tim', 3, 0], ['Jerry', 3, 0]]
Player Added
[['tim', 3, 0], ['Jerry', 3, 0]]