访问对象属性时遇到问题

时间:2013-07-20 00:21:48

标签: python

我希望使用以下语句为玩家的对象添加点数。

 players[players.index(active_player)].points += moves[active_move]

设置对象的整体代码非常简单但是我得到一个值错误,表示我输入的玩家不在列表中。补充代码如下:

class Player(object):
        def __init__(self, name):
            self.name = name
            self.points = 0

def setup(players):
    numplayers = int(raw_input("Enter number of players: "))
    for i in range(numplayers):
        name = raw_input("Enter player name: ")
        player = Player(name)
        players.append(player)

def display_moves(moves):
    for item in moves:
        print item, moves[item]

def main():
    players = []
    moves = {'Ronaldo Chop': 10, 'Elastico Chop': 30, 'Airborne Rainbow': 50, 'Fancy Fake Ball Roll': 50, 'Stop Ball and Turn': 20}
    setup(players)
    display_moves(moves)
    flag = False
    while not flag:
        active_player = raw_input("Enter a player (0 to exit):")
        if active_player == 0:
            break
        active_move = raw_input("Enter a move: ")
        players[players.index(active_player)].points += moves[active_move]

main()

2 个答案:

答案 0 :(得分:1)

这一行:

players[players.index(active_player)].points += moves[active_move]

比它需要的要复杂得多。 players.index返回players内给定对象的索引,因此您正在搜索刚刚在列表中输入的数字的位置。因此,players.index(active_player)会搜索您刚刚在玩家中输入的数字,如果找到,则会返回它位于players内的索引。由于players包含Player个对象(不是整数),因此查找将始终失败并引发异常。

我认为你要做的只是

players[active_player].points += moves[active_move]

在列表中使用active_player作为索引。 但是请注意,由于列表索引从零开始,因此您不应将零视为“退出”值,否则您将无法访问列表中的第一个播放器。

答案 1 :(得分:0)

players.index(active_player)尝试查找并返回active_playerplayers的第一个位置。 active_player是一个数字,而不是一个玩家。你只想要

players[active_player].points += moves[active_move]

(其他错误:您忘记在int的播放器输入上调用active_player。此外,列表索引从0开始,因此您可能希望在编制索引时从active_player中减去1进入players。)

相关问题