python - 使用函数迭代类
问题描述
我创建了一个类来存储游戏中的玩家。我在循环中附加玩家的详细信息以创建对象。我对如何最好地存储当前播放器的详细信息(列表中的第一个)以及如何使用函数前进到下一个播放器感到困惑。即第一名到第二名;第 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)
解决方案
我可能误解了一些东西,但看起来你可以将一个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
或类似的东西。
推荐阅读
- delphi - Delphi Rio 中的 TVirtualImageList 和表单继承
- javascript - 在 HTML 页面中播放 .m4a 音频文件不起作用
- r - 在 R 中用我自己的回归模型计算 R 平方
- python - pipenv 在 vs 代码中设置虚拟环境的路径
- python-3.x - 如何从 Pandas 中的 excel 文件中排除页眉和页脚
- javascript - 如何过滤编辑的数据,它应该以角度显示选择要编辑的数据
- jquery-ui - Jquery datepicker 中 .Remove() 和 .Destroy() 的区别
- python - 如何更准确地定义跟随颜色的 HSV 范围?
- node.js - 在 TypeScript 中使用全局变量 - Node Express
- vim - 如何在 VIM 中显示图标