我有一个班级参与者如下:
class Participant:
def __init__(self,name,level):
self.name = name
self.level =level
我还有另一个班级团队如下:
class Team:
def __init__(self,name):
self.name = name
我想在类Team
中创建一个方法来添加类Participant
的实例;例如:
假设myTeam
是一个空的,有效的Team实例。
还假设myParticipant1
是参与者的有效实例
myTeam.addParticipant(participant= myParticipant1)
AddParticipant
方法应将实例myParticipant1
添加到实例myTeam
。
我如何在Python中实现它?
答案 0 :(得分:0)
除了我们在评论中讨论的继承问题,这是非常简单的事情。
class Participant(object):
def __init__(self, name, level):
self.name = name
self.level = level
class Team(object):
def __init__(self, name):
self.name = name
self.participants = []
def add_participant(p):
self.participants.append(p)
样本:
my_team = Team("Monty Python")
p_info = [("Adam", 10e5), ("Joe-bob", -1)]
participants = [Participant(name, level) for name, level in p_info]
for participant in participants:
my_team.add_participant(participant)
# say that 10 times fast....
In [1]: [p.name for p in my_team.participants]
Out[1]: ["Adam", "Joe-bob"]