我想从足球运动员那里拿一份名单(其名称,目标,俱乐部......等属性很少)并将它们添加到他们的俱乐部(这是另一个类别),但似乎我遗漏了一些东西因为俱乐部的球员名单在循环中正在改变,即使它没有被召唤(我认为我没有正确管理球员的实例)。
所以,这是代码:
clubsWithGoal = []
class Player:
nickname = ""
imageURL = ""
numberOfGoal = 0
clubId = ""
def __init__(self, nickname, imageURL, clubId, numberOfGoal = 0):
self.nickname = nickname
self.imageURL = imageURL
self.clubId = clubId
self.numberOfGoal = numberOfGoal
def __str__(self):
return self.nickname
class Club:
Name = ""
ImageURL = u""
id = u""
numberOfGoal = 0
listOfPlayer = []
def __init__(self, id):
del self.listOfPlayer [:]
self.id = id
self.getData()
def __str__(self):
return self.Name
def getData(self):
try:
results = json.load(urllib.urlopen(
"http://worldcup.kimonolabs.com/api/clubs/" + self.id + "?apikey={youwon'tseeit}"))
self.ImageURL = results["logo"]
self.Name = results["name"]
except:
print(self.id)
def addGoal(self, numberOfGoalsToAdd):
self.numberOfGoal += numberOfGoalsToAdd
def addPlayer(self, player):
self.listOfPlayer.append(player)
print("added "+player.nickname+" to "+self.Name)
self.addGoal(player.numberOfGoal)
print("added the "+str(player.numberOfGoal)+" of "+player.nickname+" to "+self.Name)
所以这里是模型类,这里是必须对玩家进行排序而不起作用的函数:
def createAndOrderInClub(playerlist):
foundHisClub = False
for player in playerlist:
for club in clubsWithGoal:
# Case 1: The club already exists and the player is part of the club
if player.clubId == club.id:
club.addPlayer(player)
foundHisClub = True
break
# Case 2: The club doesn't already exist
if (foundHisClub == False):
newclub = Club(player.clubId)
newclub.addPlayer(player)
clubsWithGoal.append(newclub)
这是一个在循环内部发生变化的例子(我是java开发人员,也是Python的新手):
答案 0 :(得分:1)
listOfPlayer
容器,正如您声明的那样,是一个"类变量" (有点像java中的静态类成员),并且由于列表是可变的,因此无论何时在Club
的任何实例中修改此列表,它都将针对所有实例进行更改。
要修复它,只需将其从类定义中删除,然后在__init__
函数中初始化列表(字符串不存在问题,因为它们是不可变的):
class Club:
Name = ""
ImageURL = u""
id = u""
numberOfGoal = 0
def __init__(self, id):
self.listOfPlayer = []
self.id = id
self.getData()
答案 1 :(得分:1)
listOfPlayer = []
这是一个类属性,意味着它为Club
类的所有实例共享。如果您来自Java,您可以将其视为静态类变量。要使此列表对每个Club
类都唯一,请确保在构造函数中使用self
前缀对其进行初始化。
def __init__(self, id):
del self.listOfPlayer [:]
self.id = id
self.listOfPlayer = []
self.getData()
确保对您在课程级别定义的所有其他变量执行相同的操作:
Name = ""
ImageURL = u""
id = u""
numberOfGoal = 0
删除它们,并使用self
在构造函数中初始化它们。
答案 2 :(得分:1)
我认为问题是listOfPlayer
类中的Club
变量被声明为静态类成员,并且未在__init__
函数内初始化。此演示 http://dbgr.cc/R 证明了这一点。
除了上述错误之外,您似乎还没有将循环内的foundHisClub
变量重置为False
。我会在第一个for循环中声明foundHisClub
变量:
def createAndOrderInClub(playerlist):
for player in playerlist:
foundHisClub = False
for club in clubsWithGoal:
# Case 1: The club already exists and the player is part of the club
if player.clubId == club.id:
club.addPlayer(player)
foundHisClub = True
break
# Case 2: The club doesn't already exist
if (foundHisClub == False):
newclub = Club(player.clubId)
newclub.addPlayer(player)
clubsWithGoal.append(newclub)