我正在解决这个问题:
考虑以下类层次结构:
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)
如此编写的代码在使用傲慢教授类时会导致无限循环。
更改傲慢教授的定义,以实现以下行为:
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)
但是检查器只给了这个解决方案一半的分数。我犯了什么错误,以及这段代码失败的测试用例是什么?(我是 Python 新手,前段时间学习了有关类的知识。)
le.lecture(‘the sky is blue’)
的解决方案中是不是打错了,或者真的缺少代词“我”? - L3viathan