Override! - example


#1



Could some good man explain to me how this example works?
emp.greet(ceo)
ceo.greet(emp)
It is super confusing


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

here:

emp.greet(ceo)

the employee is greeting the ceo, so this calls the great method of Employee:

    def greet(self, other):
        print "Hello, %s" % other.name

with ceo as argument, so other (method parameter) now contains ceo (yes, we can pass instances as argument, so now other.name is like ceo.name, so it will ouput the ceo's name (Emily)

same for ceo.greet(emp), but then the other way around


#3

Ok, so you have two classes, one is an employee, and one is a CEO. The CEO is also an employee though, and so it should not only have the functions and properties of a CEO, but also those of an employee. CEO functions, will also override any normal employee functions. This example creates a new CEO named Emily, and a new employee named Steve, showing how Steve the employee will say hello, whereas Emily will say get back to work :slightly_smiling_face:, as CEO functions will override the Employee ones. Classes not only have functions, but also have variables. The init functions is automatically called when creating both classes(the CEO inherits it from the employee). So both classes have a name variable, and after creating CEO and employee objects, you can pass that variable into other object's functions(as shown here by the greet function)


#4

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