joh*_*ith 12 python oop class class-hierarchy python-2.7
我正在解决这个问题:
考虑以下类的层次结构:
Run Code Online (Sandbox Code Playgroud)class Person(object): def __init__(self, name): self.name = name def say(self, stuff): return self.name + ' says: ' + stuff def __str__(self): return self.name class Lecturer(Person): def lecture(self, stuff): return 'I believe that ' + Person.say(self, stuff) class Professor(Lecturer): def say(self, stuff): return self.name + ' says: ' + self.lecture(stuff) class ArrogantProfessor(Professor): def say(self, stuff): return 'It is obvious that ' + self.say(stuff)如上所述,当使用Arrogant Professor类时,此代码会导致无限循环.
更改ArrogantProfessor的定义,以便实现以下行为:
Run Code Online (Sandbox Code Playgroud)e = Person('eric') le = Lecturer('eric') pe = Professor('eric') ae = ArrogantProfessor('eric') e.say('the sky is blue') #returns eric says: the sky is blue le.say('the sky is blue') #returns eric says: the sky is blue le.lecture('the sky is blue') #returns believe that eric says: the sky is blue pe.say('the sky is blue') #returns eric says: I believe that eric says: the sky is blue pe.lecture('the sky is blue') #returns believe that eric says: the sky is blue ae.say('the sky is blue') #returns eric says: It is obvious that eric says: the sky is blue ae.lecture('the sky is blue') #returns It is obvious that eric says: the sky is blue
我的解决方案是:
class ArrogantProfessor(Person):
def say(self, stuff):
return Person.say(self, ' It is obvious that ') + Person.say(self,stuff)
def lecture(self, stuff):
return 'It is obvious that ' + Person.say(self, stuff)
Run Code Online (Sandbox Code Playgroud)
但是检查器只给出了这个解决方案的一半标记.我犯的错误是什么,以及此代码失败的测试用例是什么?(我是python的新手,不久前就开始学习类.)
您可能应该使用super()而不是硬连接类Person:
class ArrogantProfessor(Person):
def say(self, stuff):
return super(ArrogantProfessor, self).say(self.lecture(stuff))
def lecture(self, stuff):
return 'It is obvious that ' + super(ArrogantProfessor, self).say(stuff)
Run Code Online (Sandbox Code Playgroud)