1

我真的希望这不是重复......如果是这样,我无法在任何地方找到答案,所以我道歉。

无论如何,我的问题是,我正在编写代码,如果我获得的数据需要一个团队而不是一个玩家,我有一个包含两个 SinglePlayers(也是一个类)的类(称为 Team),然后是一些其他属性,只是字符串。问题是,当我遍历我的循环、读取 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 
4

1 回答 1

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班级做同样的事情。

于 2013-08-08T21:43:38.357 回答