我想在另一个类的函数中使用一个类的对象。我知道这是一件很容易解决的事情,但我仍然想不通。
我有以下课程是玩家的对象
class Players():
def __init__(self, name_player, surname, age, height, wheight):
self.name_player= name_player
self.surname = surname
self.age= age
self.height= height
self.wheight= wheight
def __repr__(self):
return "{}, {}, {}, {}, {} //".format(self.name_player,self.surname,self.age,self.height,self.wheight)
那我就属于这类团队
class Teams():
def __init__(self, name, points, goals_in_favour, goals_against):
self.name= name
self.points= points
self.goals_in_favour= goals_in_favour
self.goals_against= goals_against
def __repr__(self):
return "{} : {} : {}: {}".format(self.name,self.points,self.goals_in_favour,self.goals_against)
现在在“年龄”函数中,我希望它返回年龄小于或等于文件上年龄的球员列表。如果我写“ i.Players.age”,它将向我发送错误,这是正确的拼写方式?
def ages(lists_teams,age):
list_players =""
return [list_players + i for i in list_teams if (i.Players.age <= age)]
(我必须以列表理解的方式编写它。)
非常感谢。
答案 0 :(得分:1)
以帮助您理解。
1。如果list_teams已经是对象列表...您不能调用i.Players,因为我这里已经是对象。
2.list_players =“”您应该将其更改为[]。...“”不是列表,您不能在其上添加对象。
3。尽量不要将i用作对象,通常用于指示索引。
def ages(list_teams,age):
list_players =[]
return [list_players + [player] for player in list_teams if (player.age <= age)]