首页 > 解决方案 > 使用函数迭代类

问题描述

我创建了一个类来存储游戏中的玩家。我在循环中附加玩家的详细信息以创建对象。我对如何最好地存储当前播放器的详细信息(列表中的第一个)以及如何使用函数前进到下一个播放器感到困惑。即第一名到第二名;第 2 到第 3 等等。使用字典而不是类会更好吗?任何想法都非常感激。

class Player:  # Create a class and structure
    score = 0

    def __init__(self, pnum, name, score, round):
        self.pnum = pnum
        self.name = name
        self.score = score
        self.round = round


def CreatePlayers():

    a = int(input("Please enter the number of players\t "))

    player = []  # Create List Array

    for i in range(a):  # populate list using class
        player.append(Player(i, input("Enter Name:\t"), 0, 0))

    print("\n")

    for x in range(len(player)):  # print from class
        print(player[x].pnum, player[x].name, "\tScore:\t ", player[x].score,
              "\tRound:\t ", player[x].round)

    global current_player
    current_player = (player[0].pnum, player[0].name, player[0].score,
                      player[0].round)

标签: pythonfunctionclassiteration

解决方案


我可能误解了一些东西,但看起来你可以将一个Player对象分配给current_player

# The current player will now be the first player
current_player = player[0]
# Iterate over all players in the order they're created:
for i in range(len(player)):
    current_player = player[i]
    print("Currently playing: player {}".format(i))
    current_player.some_method()

.some_method()如果需要,可以负责更新播放器的详细信息。

您的代码中有点令人困惑的一件事是调用数组player而不是调用数组players或类似的东西。


推荐阅读