Understanding code example on Overriding


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/2/3?curriculum_id=4f89dab3d788890003000096


I have mentioned the code snippet below. I think that the explanation to the code is extremely vague particularly since i have seen most examples dissected and explained exhaustively. For example, I would like the reader to kindly explain what happens when ceo = CEO("Emily") is created. To what does the string "Emily" bind itself to?

What happens when emp.greet(ceo) is called?
What's happening with the variables in each of the function call?

class Employee(object):
    def __init__(self, name):
        self.name = name
    def greet(self, other):
        print "Hello, %s" % other.name

class CEO(Employee):
    def greet(self, other):
        print "Get back to work, %s!" % other.name

ceo = CEO("Emily")
emp = Employee("Steve")
emp.greet(ceo)
# Hello, Emily
ceo.greet(emp)
# Get back to work, Steve!


#2

Hi, @mickey005 ,

Since the CEO class definition does not include a new definition for the __init__ method, the CEO class inherits that method from the parent Employee class. Therefore, this instantiation and assignment ...

ceo = CEO("Emily")

... assigns the string, "Emily" to an instance variable named name that belongs to the new ceo object, as this statement executes ...

self.name = name

Both greet methods include the expression, other.name, as part of what is output. In both cases, other refers to the object that is passed as an argument in parentheses when the greet method is called.

Therefore, here ...

emp.greet(ceo)

... the ceo object's name instance variable, which has the value, "Emily", is included in the output.

Here ...

ceo.greet(emp)

... emp's name instance variable, which has the value, "Steve", is part of the output.


#3

Thank you @appylpye. It's much clearer now.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.