ENGR 101 Introduction To Programming: Week 14
ENGR 101 Introduction To Programming: Week 14
Introduction to
Programming
Week 14
Reminder
Last Week (Week 13)
Classes and Methods
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return str(self.hour) + ':' + str(self.minute) + ':' + str(self.second)
def print_time(self):
print str(self.hour) + ':' + str(self.minute) + ':'\
+ str(self.second)
def time_to_int(self):
minutes = self.hour * 60 + self.minute
seconds = minutes * 60 + self.second
return seconds
def int_to_time(self,seconds):
hour = (seconds / 3600) % 24
minute = (seconds /60) % 60
second = seconds % 60
return Time(hour, minute, second)
# Type-based dispatch
def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
def sale_price(self):
"""Return the sale price for this car."""
return 5000 * self.wheels
def purchase_price(self):
"""Return the price for which we would pay to purchase the car."""
return 8000 - (0.10 * self.kilometers)
Dealership - Truck Class
class Truck:
wheels = 10
def __init__(self, kilometers, make, model, year):
"""Return a new Truck object."""
self.kilometers = kilometers
self.make = make
self.model = model
self.year = year
def sale_price(self):
"""Return the sale price for this truck"""
return 5000 * self.wheels
def purchase_price(self):
"""Return the price for which we would pay to purchase the truck."""
return 10000 - (0.10 * self.kilometers)
Dealership - Motorcycle Class
class Motorcycle:
wheels = 10
def __init__(self, kilometers, make, model, year):
"""Return a new Truck object."""
self.kilometers = kilometers
self.make = make
self.model = model
self.year = year
def sale_price(self):
"""Return the sale price for this truck"""
return 5000 * self.wheels
def purchase_price(self):
"""Return the price for which we would pay to purchase the truck."""
return 4000- (0.10 * self.kilometers)
Problems?
• Solution:
Inheritance!: Introduce base class that will capture the
shared parts of Car and Truck classes
Add Vehicle class as our base class
Derive Car, Truck and Motorcycle classes from Vehicle
Dealership – Vehicle Class
class Vehicle:
flat_rate = 0
wheels = 0
def __init__(self, kilometers, make, model, year):
"""Return a new Vehicle object."""
self.kilometers = kilometers
self.make = make
Our “base” class
self.model = model that
self.year = year
accommodates
def sale_price(self): the shared parts
return 5000 * self.wheels
def purchase_price(self):
return self.flat_rate - (0.10 * self.kilometers)
def vehicle_advertisement_text(self):
pass
Inheritance: Car and Truck
class Car(Vehicle):
flat_rate = 8000
wheels = 4
Syntax for
inheritance
def vehicle_advertisement_text (self):
return 'Car - ' + str(self.year) + ' ' + self.make + ' ' + \
self.model + ' - ' + str(self.kilometers) + ' km'
class Truck(Vehicle):
flat_rate = 10000 Method
wheels = 10
overriding
def vehicle_advertisement_text (self):
return ‘Truck - ' + str(self.year) + ' ' + self.make + ' ' + \
self.model + ' - ' + str(self.kilometers) + ' km'
Adding a new class: Motorcycle
class Motorcycle(Vehicle):
flat_rate = 4000
wheels = 2
• Solution:
Move the common/repeated part to the base class under
vehicle_advertisement_text method.
Call base class’es vehicle_advertisement_text
method in child classes’
vehicle_advertisement_text method.
class Vehicle(object):
... Move the common parts to
... Inherit the built-in
... the base class method
object class
def vehicle_advertisement_text(self):
return str(self.year) + ' ' + self.make + ' ' + \
self.model + ' - ' + str(self.kilometers) + ' km'
class Truck(Vehicle):
flat_rate = 10000
wheels = 10
def vehicle_advertisement_text (self):
return 'Truck - ' + super(Truck, self).vehicle_advertisement_text()
class Motorcycle(Vehicle):
flat_rate = 4000
wheels = 2
def vehicle_advertisement_text(self):
return 'Motocycle-' + super(Motorcycle, self).vehicle_advertisement_text()
class Cat:
def __init__(self, name):
self.name = name
class Dog:
def __init__(self, name):
self.name = name
Talking Animals
animals = [Cat('Missy'),
Cat('Mistof'),
Dog('Lassie')]
# output:
# Missy: Meow!
# Mistof: Meow!
# Lassie: Woof!
Problem?
def talk(self):
return ‘what?’
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof!'
Solution: Polymorphism
animals = [Cat('Missy'),
Cat('Mistof'),
Dog('Lassie')]
# output:
#
# Missy: Meow!
# Mistof: Meow!
# Lassie: Woof!
Polymorphism
Clubs
Spades
A deck of cards
Card objects
class Card(object):
"""represents a standard playing card."""
def __str__(self):
return Card.rank_names[self.rank] + ‘ of ’ + \
Card.suit_names[self.suit]
Comparing cards –
Operator Overloading
• For built-in types, there are relational operators (<, >, ==, etc.)
that compare values and determine when one is greater than, less
than, or equal to another.
• For user-defined types, we can override the behavior of the built-
in operators by providing a method named __cmp__.
• __cmp__ takes two parameters, self and other, and returns a
positive number if the first object is greater, a negative number if
the second object is greater, and 0 if they are equal to each other.
Comparing cards – Operator
Overloading
class Deck(object):
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
Printing the Deck
deck = Deck()
print deck
Ace of Clubs
#inside class Deck:
def __str__(self): 2 of Clubs
res = [] 3 of Clubs
for card in self.cards: ...
res.append(str(card))
return '\n'.join(res) 10 of Spades
Jack of Spades
Queen of Spades
King of Spades
Add, remove, shuffle,
and sort
class Hand(Deck):
"""represents a hand of playing cards"""
• This definition indicates that Hand inherits from Deck;
that means we can use methods like pop_card and
add_card for Hand objects as well as Deck objects.
Inheritance - Overriding
Write a class named Player that will inherit from Game class
and implement a create_new_castle method
which will allow the player to create a new castle if his
energy is >5 and his money is > 10,
it should update the attributes accordingly.
Exercise 2:
• Create another class OponentPlayer that will inherit from
class Game written before and
it will have an additional attribute named
no_of_destructions.
•
Implement a method that will destroyCastle() which will allow
the player to destroy a castle, thereby increasing his
no_of_destructions attribute.
•
If the player’s energy is lower than 10, he won’t be able to
destroy the castle.