Python - Write program to Create class hierarchy, relationships "is-a"

Requirements

Our product shop team can be defined by the four classes.

The most general class, Employee, provides common behavior such as bumping up salaries (giveRaise) and printing (__repr__).

There are two kinds of employees, and so two subclasses of Employee-Chef and Server.

Both override the inherited work method to print more specific messages.

Our product robot is modeled by ProductRobot which is a kind of Chef

Hint

In OOP terms, we call these relationships "is-a" links: a robot is a chef, which is an employee.

Demo

from __future__ import print_function 

class Employee: # w w  w .  j ava 2s.  c  o  m
    def __init__(self, name, salary=0): 
        self.name   = name 
        self.salary = salary 
    def giveRaise(self, percent): 
        self.salary = self.salary + (self.salary * percent) 
    def work(self): 
        print(self.name, "does stuff") 
    def __repr__(self): 
        return "<Employee: name=%s, salary=%s>" % (self.name, self.salary) 

class Chef(Employee): 
    def __init__(self, name): 
        Employee.__init__(self, name, 50000) 
    def work(self): 
        print(self.name, "makes food") 

class Server(Employee): 
    def __init__(self, name): 
        Employee.__init__(self, name, 40000) 
    def work(self): 
        print(self.name, "interfaces with customer") 

class ProductRobot(Chef): 
    def __init__(self, name): 
        Chef.__init__(self, name) 
    def work(self): 
        print(self.name, "makes product") 

if __name__ == "__main__": 
    bob = ProductRobot('bob')       # Make a robot named bob 
    print(bob)                    # Run inherited __repr__ 
    bob.work()                    # Run type-specific action 
    bob.giveRaise(0.20)           # Give bob a 20% raise 
    print(bob); print() 

    for klass in Employee, Chef, Server, ProductRobot: 
        obj = klass(klass.__name__) 
        obj.work()

Result

Related Quiz