Tôi đang giải quyết vấn đề này:Lớp kế thừa trong python
Hãy xem xét các hệ thống phân cấp sau các lớp:
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)
Theo văn bản, mã này dẫn đến một vòng lặp vô hạn khi sử dụng lớp Giáo sư Arrogant .
Thay đổi định nghĩa của ArrogantProfessor để các hành vi sau được thực hiện:
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
Giải pháp của tôi cho điều này là:
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)
Nhưng kiểm tra cho chỉ dấu nửa cho giải pháp này . Sai lầm mà tôi đang mắc phải là gì và các trường hợp thử nghiệm mà mã này không thành công? (Tôi mới vào python và tìm hiểu về các lớp học một số thời gian trước đây.)
Có phải đó là một lỗi đánh máy trong các giải pháp cho ' le.lecture ('bầu trời xanh') ', hay thực sự đại từ" tôi "bị thiếu? – L3viathan
@ L3viathan đó là lỗi đánh máy –