面向对象编程python

时间:2013-03-16 20:13:52

标签: python oop python-3.x

我需要实现一个名为athlete的类,它需要__init__(self,names,fastest_time) 另一个名为fastest_time的方法,它将显示最快运动员的名字和时间:

到目前为止,我有这个:

class Athlete:
    def __init__(self,names,ftime):
        self.name=names
        self.fastest=ftime
    def fastest_athlete(self):


names=(['sara','jam','mary'])
times=([90,50,75])
a=Athlete(name,ftime)
a.fastest_athlete()

问题:不知道是否需要遍历数组名称' times'?不知道如何实现方法rapid_time..HELP PLEASE

5 个答案:

答案 0 :(得分:2)

你应该遍历数组以创建Athlete s。

>>>Athletes = [Athlete(name, time) for name, time in zip(names, times)]    
>>>Athletes[0].name
sara
>>>Athletes[1].name
jam

好吧,为了找到最快的运动员,你可以使用maxmin功能。

>>>min(Athletes, key = lambda a : a.fastest)

但您应该注意min()是在包含Athlete的数组上完成的,而不是Athlete本身。如果你想找到最快的Athlete,你可能需要AthleteContainer类。

答案 1 :(得分:1)

由于最快的运动员不依赖于具体的实例,因此它更适合作为静态方法:

class Athlete:
    # ...
    @staticmethod
    def fastest_athlete(athletes):
        return reduce(lambda x, y: x if x.fastest < y.fastest else y, athletes)

# ...
athletes = [Athlete(name, time) for name, time in zip(names, times)] 
fastest = Athlete.fastest_athlete(athletes)

答案 2 :(得分:0)

如果您希望fastest_athlete成为运动员课程的一部分,那么您的Athlete课程应该能够覆盖所有运动员。

fastest_athlete会返回一个列表,因为可能会有更多运动员跑出最佳时间。

athletes=[] # stores all athletes 

class Athlete:
    def __init__(self,names,ftime):
        self.name=names
        self.fastest=ftime
        athletes.append(self)
    def fastest_athlete(self):
        besttime= min([athlete.fastest for athlete in athletes])
        return [athlete.name for athlete in athletes if athlete.fastest==besttime]



names=(['sara','jam','mary'])
times=([90,50,75])

for a, t in zip(names, times):
    last_athlete=Athlete(a, t)

print last_athlete.fastest_athlete()

答案 3 :(得分:0)

如果您只想循环遍历数组self.name,那么:

for name in self.names:
    # Do something

但对于实际问题:

def fastest_athlete(self):
    combined = zip(self.names, self.fastest)

    #Note that this will return the athlete with the first fastest time if there are dupes
    index = self.fastest.index(min(self.fastest))

    #If you want multiples:
    indices = [i for i,n in enumerate(self.fastest) if n == min(self.fastest)]

    #Either return the list (combined[0] is the athlete's name, combined[1] is the associated time) or print it here.
    return combined[index]

但是,我同意另一位评论者 - 运动员应该是单独的对象,而不是集合。

答案 4 :(得分:0)

您可以覆盖__gt__方法并使用python的max函数。此外,每个班级应代表一名运动员,而不是运动员名单。

>>> class Athlete:
    name = None
    time = None

    def __init__(self, name, time):
        self.name = name
        self.time = time

    def __gt__(self, other):
        return self.time > other.time

>>> names = ['sara', 'jam', 'mary']
>>> times = [90 ,50 , 75]
>>>
>>> athletes = [Athlete(name, time) for name, time in zip(names, times)]
>>>
>>> fastest = max(athletes)
>>> fastest.name
'sara'
>>> fastest.time
90