Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inheritance in python

I am solving this problem :

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

My solution to this is:

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)

But the checker gives only half marks for this solution. What is the mistake that I am making and what are the test cases on which this code fails? (I am new to python and learned about classes some time ago.)

like image 694
sid597 Avatar asked Mar 12 '16 22:03

sid597


1 Answers

You probably should use super() instead of hard-wiring the class 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)
like image 126
Mike Müller Avatar answered Oct 20 '22 21:10

Mike Müller