Understanding code example on Overriding



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")
# Hello, Emily
# Get back to work, Steve!


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 ...


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

Here ...


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


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


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