13.Override!


#1



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


Here I just want to discuss the example they gave us at left console


I am not very clear with the code below:
ceo = CEO("Emily") # which attributes was assigned with the value " Emily " ? the one in class CEO or the one in class Employee ?
emp = Employee("Steve")
emp.greet(ceo) #What does this line mean ?
ceo.greet(emp) # the same as above

and why it does not print anything at first two lines above but return the words at last two lines?


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

what you do here, is creating a class instance (ceo) of class CEO. But because CEO inherits from Employee, __init__() of Employee is called. (unless you add an __init__() to CEO, which would override Employee __init__())

an employer (emp) greets ceo, which results in: Hello, Emily

the ceo greets the employer: Get back to work, Steve!

the first two lines, which i assume refer to this:

ceo = CEO("Emily")
emp = Employee("Steve")

you create class instances, which doesn't print anything. When you call the .greet() method which has a print statement in it, something will be printed


#3

Thank you! It's really clear and helpful.
Wish you a happy April fool~


#4

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