我真的希望这不是重复...如果是,我无法在任何地方找到答案,所以我道歉。
无论如何,我的问题是,我正在编写代码,如果我获得的数据需要团队而不是玩家,我有一个类(称为Team),它拥有两个SinglePlayers(也是一个类),然后是很少有其他属性,只是字符串。问题是,当我遍历我的循环,读取xml数据并填满我的“团队”变量时,似乎SinglePlayers的所有信息都没有被重置。这是一个问题,因为每当我将新的“团队”插入到我所拥有的“团队”对象列表中时,它就会更改该信息。代码很长,所以我只会发布相关内容。
我再次使用python几天了。我在过去的一年里一直在java和c ++工作,所以我的大脑在变量和结构如何工作的头脑中有这些概念。我知道python是不同的,所以如果有人可以请说明为什么这不起作用,那将是惊人的。谢谢!
class SinglePlayer:
entry_code = ""
first_name = ""
last_name = ""
nation = ""
seed_rank_sgl = ""
seed_rank_dbl = ""
entry_rank_sgl = ""
entry_rank_dbl = ""
class Team:
top_player = SinglePlayer()
bottom_player = SinglePlayer()
entry_code = ""
seed_rank = ""
entry_rank = ""
def DoublesEvent(self, team_nodes):
#Create List to store team objects
teams_list = []
for k in range(0, team_nodes.length):
#Get the current node
teams_node = team_nodes.item(k)
team_node = team_nodes.item(k).getElementsByTagName("Player")
top_player_node = team_node.item(0)
bottom_player_node = team_node.item(1)
#Make a new team object to fill and add to teams_list
team = Team()
team.entry_code = teams_node.getAttribute("EntryCode")
#Top Player Info
team.top_player.first_name = top_player_node.getAttribute("FirstName")
team.top_player.last_name = top_player_node.getAttribute("LastName")
team.top_player.nation = top_player_node.getAttribute("Nation")
#Bottom Player Info
team.bottom_player.first_name = bottom_player_node.getAttribute("FirstName")
team.bottom_player.last_name = bottom_player_node.getAttribute("LastName")
team.bottom_player.nation = bottom_player_node.getAttribute("Nation")
eam.seed_rank = self.GetSeedRank(team)
team.entry_rank = self.GetEntryRank(team)
#Add the team to the list
teams_list.append(team)
return teams_list
答案 0 :(得分:3)
您的类包含对两个SinglePlayer()
实例的引用,而不是您的实例。使用__init__
方法为每个Team
实例创建新实例:
class Team:
entry_code = ""
seed_rank = ""
entry_rank = ""
def __init__(self):
self.top_player = SinglePlayer()
self.bottom_player = SinglePlayer()
实际上,因为您重新绑定了您创建的实例上的每个字符串属性,所以发生以为这些属性创建实例属性。你最好还是将它们转移到__init__
并将它们的关系作为实例属性明确表示:
class Team:
def __init__(self):
self.entry_code = ""
self.seed_rank = ""
self.entry_rank = ""
self.top_player = SinglePlayer()
self.bottom_player = SinglePlayer()
并为您的SinglePlayer
课程执行相同操作。