Первый файл содержит только элементы наследования, второй — содержит класс-конструктор. Объекты, созданные из класса конструктора, состоят из других объетов, созданных на основе других классов. Так в примере ниже объект-сцена имеет в своем составе «клиента», «официанта», «повара» и «печь».
class Employee:
def __init__(self, name, salary=0):
self.name = name
self.salary = salary
def giveRaise(self, percent):
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 PizzaRobot(Chef):
def __init__(self, name):
Chef.__init__(self, name)
def work(self):
print(self.name, "makes pizza")
if __name__ == "__main__":
bob = PizzaRobot('Bob')
print(bob)
bob.work()
bob.giveRaise(0.2)
print(bob,'\n')
for klass in Employee, Server, PizzaRobot:
obj = klass(klass.__name__)
obj.work()
from employees import Server, PizzaRobot
class Customer:
def __init__(self, name):
self.name = name
def order(self, server):
print(self.name, "orders from", server)
def pay(self, server):
print(self.name, "pays for item to", server)
class Oven:
def bake(self):
print("oven bakes")
class PizzaShop:
def __init__(self):
self.server = Server('Pat') # свойство объекта является объектом
self.chef = PizzaRobot('Bob')
self.oven = Oven()
def order(self, name):
customer = Customer(name)
customer.order(self.server)
self.chef.work()
self.oven.bake()
customer.pay(self.server)
if __name__ == "__main__":
scene = PizzaShop()
scene.order('Homer')
print('\n')
scene.order('Tom')
class Lunch:
def __init__(self):
self.cust = Customer()
self.empl = Employee()
def order(self,foodName):
self.cust.placeOrder(foodName,self.empl)
def result(self):
self.cust.printFood()
class Customer:
def __init__(self):
self.food = None
def placeOrder(self,foodName,employee):
self.food = employee.takeOrder(foodName)
def printFood(self):
print (self.food.name)
class Employee:
def takeOrder(self,foodName):
return Food(foodName)
class Food:
def __init__(self,name):
self.name = name
if __name__ == '__main__':
x = Lunch()
x.order('soop')
x.result()