在python中将一个类的对象添加到另一个类的对象中

时间:2015-02-20 23:16:49

标签: python

我有一个班级参与者如下:

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中实现它?

1 个答案:

答案 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"]