gpt4 book ai didi

python - python中的类继承

转载 作者:太空狗 更新时间:2023-10-29 17:42:43 25 4
gpt4 key购买 nike

我正在解决这个问题:

Consider the following hierarchy of classes:

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)

As written, this code leads to an infinite loop when using the Arrogant Professor class.

Change the definition of ArrogantProfessor so that the following behavior is achieved:

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,前段时间学习了类。)

最佳答案

您可能应该使用 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)

关于python - python中的类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com