Python - Write program to implement "Has-a" Relationships


The product shop is a composite object: it has an oven, and it has employees like servers and chefs.

When a customer enters and places an order, the components of the shop spring into action-the server takes the order, the chef makes the product, and so on.


Composition reflects the relationships between parts, called "has-a" relationships.


from __future__ import print_function 

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

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

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

class ProductRobot(Chef): 
    def __init__(self, name): 
        Chef.__init__(self, name) 
    def work(self): 
        print(, "makes product") 
class Customer: 
    def __init__(self, name): = name 
    def order(self, server): 
        print(, "orders from", server) 
    def pay(self, server): 
        print(, "pays for item to", server) 

class Oven: 
    def bake(self): 
        print("oven bakes") 

class ProductShop: 
    def __init__(self): 
        self.server = Server('Pat')    # Embed other objects 
        self.chef   = ProductRobot('Bob')# A robot named bob 
        self.oven   = Oven() 

    def order(self, name): 
        customer = Customer(name)  # Activate other objects 
        customer.order(self.server)# Customer orders from server 

if __name__ == "__main__": 
    scene = ProductShop()            # Make the composite 
    scene.order('Java')            # Simulate Java's order 
    scene.order('Javascript')      # Simulate Javascript's order


Related Quiz