Skip to content

Question 28

What is the output of the following code?

class Person():
    def __init__(self, name):
        self.name = name
    def intro(self):
        print('Hi, this is ' + self.name)

class Adult(Person):
    def __init__(self, name):
        super().__init__(name)
        self.spouse = None
    def marry(self, spouse):
        self.spouse = spouse

rachel = Adult('Rachel')
rachel.marry(Adult('Ross'))
rachel.spouse.intro()
Hint

Notice that the Adult class is a child class of Person. This would mean Adult inherits class members and methods from Person.

Solution

A similar implementation of the Adult class while taking into account class members and methods from Person could go something like this:

1
2
3
4
5
6
7
8
9
# if you consolidate Person's class members and methods into Adult
class Adult:
    def __init__(self, name):
        self.name = name
        self.spouse = None
    def intro(self):
        print('Hi, this is ' + self.name)
    def marry(self, spouse):
        self.spouse = spouse

Create an Adult object named "Rachel" first. This will initialize the object's name class member to "Rachel" and spouse to None. From the marry() method that comes later, we can possibly infer that spouse is suppose to be of an object value type. This is further confirmed with the execution of statement rachel.marry(Adult('Ross')), where object Adult('Ross') is passed in to be set as the value of rachel.spouse. Running rachel.spouse.intro() only invokes the intro() method of Adult('Ross').

Answer
Hi, this is Ross