Object-Oriented Programming Tutorial

Object-Oriented Programming Tutorial

class Human:
  def __init__(self, name):
    self.name = name
    self.energy = 10
    self.friends = []

  def __str__(self):
    s = 'Hi, my name is {0}'.format(self.name)
    return s
  
  def move(self, steps=1):
    if self.energy < steps:
      print("I don't have the energy to walk that far")
    else:
      self.energy -= steps
  
  def sleep(self):
    self.energy = 10
  
  def makefriend(self, friend):
    self.friends.append(friend)
    friend.friends.append(self)
  
a = Human('Alice')
b = Human('Bruno')
c = Human('Chantel')
print(a)
a.move(3)
print(a.energy)
Hi, my name is Alice
7
a.makefriend(b)
a.makefriend(c)
print("Alice's friends: ")
for i in a.friends:
  print(i.name)

print("\nBruno's friends: ")
for i in b.friends:
  print(i.name)
Alice's friends: 
Bruno
Chantel

Bruno's friends: 
Alice
class Bakery:
  def __init__(self, cookies, cost):
    self.numcookies = cookies
    self.cost = cost

  def __str__(self):
    s = 'This Bakery has {0} cookies at ${1} each'.format(self.numcookies,
                                                          self.cost)
    return s
class Baker(Human):
  def __init__(self, name):
      super().__init__(name)
      self.sales = 0
  
  def make_cookies(self, bakery, n_cookies):
    bakery.numcookies += n_cookies
  
  def sell_cookies(self, customer, bakery, n_cookies):
    if n_cookies > bakery.numcookies:
      print("This bakery doesn't have {0} cookies to sell".format(n_cookies))
      return
    
    subtotal = n_cookies * bakery.cost
    if customer.money < subtotal:
      print("The customer can't afford these cookies.")
      return


    bakery.numcookies -= n_cookies
    self.sales += subtotal
    customer.money -= subtotal
    customer.cookies += n_cookies
class Customer(Human):
  def __init__(self, name, money):
    super().__init__(name)
    self.money = money
    self.cookies = 0

  def __str__(self):
    s = super().__str__() + ' and I have {0} cookies'.format(self.cookies)
    return s
romina = Baker('Romina')
print(romina)
Hi, my name is Romina
kelsey = Customer('Kelsey', 10)
print(kelsey)
Hi, my name is Kelsey and I have 0 cookies
my_bakery = Bakery(20, 1.25)
print(my_bakery)
This Bakery has 20 cookies at $1.25 each
romina.sell_cookies(kelsey, my_bakery, 5)
print(kelsey)
print(kelsey.money)
print(my_bakery)
Hi, my name is Kelsey and I have 5 cookies
3.75
This Bakery has 15 cookies at $1.25 each