我有一个对象列表,我想将一个不同的项目附加到每个对象的列表属性中。我想使用循环来做到这一点:
当我尝试使用循环时,该项目将附加到列表中的所有对象,而不仅仅是选定的对象。 如果我手动将值分配给一个单独的对象,则仅该对象 保留新值,这是期望的结果。
"""
simple class example (The one I'm using has a lot more attributes so I
thought it would be easier to do a simple example)
"""
class Player():
name = ""
hand = []
player_1 = Player(name = 'Dealer')
player_2 = Player(name = 'Bob')
player_list = [player_1,Player_2]
# assign one random integer to each players hand __once__ and shows the hand
for player in player_list:
player.hand.append(random.randint(1,10))
print(player.name)
print(player.hand)
print()
# spacer
print('-----------\n')
# assign a new hand to player_2 directly
player_list[1].hand = ['1s','1h','1d','1c','2s']
#show player hands
for player in player_list:
print(player.name)
print(player.hand)
print()
期望的结果将是:
Bob
Dealer
[7]
Bob
[4]
-----------
Dealer
[7]
Bob
['1s', '1h', '1d', '1c', '2s']
实际结果是:
Bob
Dealer
[7]
Bob
[7, 4]
-----------
Dealer
[7, 4]
Bob
['1s', '1h', '1d', '1c', '2s']