st1 Week 09 Tut Lab Solutions Updated
st1 Week 09 Tut Lab Solutions Updated
TUTORIAL ACTIVITIES: All tutorial questions focus on Python 3.0 and above versions.)
1. In the table shown below for the Triangle class definition code, identify the error
2. Assume the Circle class shown below is defined in a python file circle.py. And in a separate
python file called circle_tester.py, the circle objects are created. Show the output produced
by each code fragment in Table 2 below.
###### circle.py ######
class Circle:
def __init__(self, radius=1):
self.radius = radius
def getRadius(self):
return self.radius
def area(self):
return 3.14 * self.radius * self._radius
def circumference(self):
return 2 * 3.14 * self.radius
circle_tester.py Output
import circle 1
c = circle.Circle()
print(c.getRadius())
import circle 4
c = circle.Circle(4)
print(c.getRadius())
import circle 5
c = circle.Circle()
c.setRadius(5)
print(c.getRadius())
import circle 12.56
c = circle.Circle(2)
print(c.area())
import circle 18.84
c = circle.Circle(3)
print(c.circumference())
import circle 18.84
c = circle.Circle()
c.setRadius(3)
print(c.circumference())
import circle 12.56
c = circle.Circle()
c.setRadius(2)
print(c.area())
Look at the following code examples, which is the first line of a class definition. What is the name of
the superclass? What is the name of the subclass?
a. class Canary(Bird):
b. class Hammer(Tool):
1. Write the first line of the definition for a Trout Class. The class should extend/inherit
the Fish Class.
class Trout(Fish):
class Art:
def __init__(self, art_type):
self.__art_type = art_type
def message(self):
print("I'm a piece of art.")
class Painting(Art):
def __init__(self):
Art.__init__(self, 'painting')
def message(self):
print("I'm a painting.")
Given these class definitions, what will the following statements display?
a = Art('sculpture')
p = Painting()
a.message()
p.message()
class Vegetable:
def __init__(self, vegtype):
self.__vegtype = vegtype
def message(self):
print("I'm a vegetable.")
class Potato(Vegetable):
def __init__(self):
Vegetable.__init__(self, 'potato')
def message(self):
print("I'm a potato.")
Given these class definitions, what will the following statements display?
v = Vegetable('veggie')
p = Potato()
v.message()
p.message()
I'm a vegetable.
I'm a potato.
4. Suppose a program uses two classes: Airplane and JumboJet. Which of these would most
likely be defined the superclass and the subclass?
Jumbojet is superclass
Airplane is subclass
Is Airplane a jumbojet ? No !
LABORATORY ACTIVITIES:
Solution:
class EmployeeWages:
def __init__(self, name="", hours=0.0, wage=0.0):
self.name = name
self.hours = hours # Number of hours worked during week
self.wage = wage # Hourly wage
def getName(self):
return self.name
def getHours(self):
return self.hours
def getWage(self):
return self.wage
def payForWeek(self):
amount = self.hours * self.wage
if self.hours > 40:
amount = 40 * self.wage + ((self.hours - 40)*(1.5 * self.wage))
return "${0:,.2f}".format(amount)
def main():
## Calculate a workers weekly pay.
print("=== Object Oriented Employee Wages Calculator ===")
emp_1 = EmployeeWages()
name = input("Enter Employee's name: ")
emp_1.setName(name)
hours = float(input("Enter number of hours worked: "))
emp_1.setHours(hours)
wage = float(input("Enter hourly wage: "))
emp_1.setWage(wage)
print("Pay for", emp_1.getName() + ':', emp_1.payForWeek())
main()
def payForWeek(hours,wage):
amount = hours * wage
if hours > 40:
amount = 40 * wage + ((hours - 40)*(1.5 * wage))
return "${0:,.2f}".format(amount)
main()
Write an object-oriented shopping cart console program that checks out the items in the
user’s cart on a shopping website. The program should use a class named Shop to hold the
information about a single item purchased (that is, description, price, and quantity) and a
class named Cart to hold a list whose items are objects of type Shop. Draw the UML class
diagram as well.
A successful test run of the program is as shown in screenshot below:
Solution:
ShoppingCart.py
class Shop:
def __init__(self, description="", price=0, quantity=0):
self.description = description
self.price = price
self.quantity = quantity
def getDescription(self):
return self.description
def getPrice(self):
return self.price
def getQuantity(self):
return self.quantity
class Cart:
def __init__(self, items=[]):
self.items = items
def getItems(self):
return self.items
def calculateTotal(self):
amount = 0
for item in self.items:
amount += item.getPrice() * item.getQuantity()
return amount
ShoppingCart_Tester.py
import ShoppingCart
from ShoppingCart import Cart,Shop
def main():
## Check out at a shopping Web site.
myPurchases = Cart()
carryOn = 'Y'
while carryOn.upper() == 'Y':
description = input("Enter description of article: ")
price = float(input("Enter price of article: "))
quantity = int(input("Enter quantity of article: "))
article = Shop(description, price, quantity)
myPurchases.addItemToCart(article)
carryOn = input("Do you want to enter more articles (Y/N)? ")
printReceipt(myPurchases)
def printReceipt(myPurchases):
print("\n{0:12} {1:<s} {2:<12}".format("ARTICLE", "PRICE", "QUANTITY"))
for purchase in myPurchases.getItems():
print("{0:12s} ${1:,.2f} {2:5}".format(purchase.getDescription(),
purchase.getPrice(), purchase.getQuantity()))
print("\nTOTAL COST: ${0:,.2f}".format(myPurchases.calculateTotal()))
main()
Testing:
UML Class Diagram for shopping cart and tester (using gitUML - https://www.gituml.com/)
Improved Object Oriented Shopping Cart with MVC Pattern(Model View Controller)
Pattern
ShoppingCart_Model.py
class Shop:
def __init__(self, description="", price=0, quantity=0):
self.description = description
self.price = price
self.quantity = quantity
def getDescription(self):
return self.description
def getPrice(self):
return self.price
def getQuantity(self):
return self.quantity
ShoppingCart_Controller.py
class Cart:
def __init__(self, items=[]):
self.items = items
def getItems(self):
return self.items
def calculateTotal(self):
amount = 0
for item in self.items:
amount += item.getPrice() * item.getQuantity()
return amount
ShoppingCart_View.py
import ShoppingCart_Model
import ShoppingCart_Controller
from ShoppingCart_Model import Shop
from ShoppingCart_Controller import Cart
def main():
## Check out at a shopping Web site.
myPurchases = Cart()
carryOn = 'Y'
while carryOn.upper() == 'Y':
description = input("Enter description of article: ")
price = float(input("Enter price of article: "))
quantity = int(input("Enter quantity of article: "))
article = Shop(description, price, quantity)
myPurchases.addItemToCart(article)
carryOn = input("Do you want to enter more articles (Y/N)? ")
printReceipt(myPurchases)
def printReceipt(myPurchases):
print("\n{0:12} {1:<s} {2:<12}".format("ARTICLE", "PRICE", "QUANTITY"))
for purchase in myPurchases.getItems():
print("{0:12s} ${1:,.2f} {2:5}".format(purchase.getDescription(),
purchase.getPrice(), purchase.getQuantity()))
print("\nTOTAL COST: ${0:,.2f}".format(myPurchases.calculateTotal()))
main()
3. Object Oriented Person Information System Design and Development
Design a class that holds the following personal data: name, address, age, and
phone number. Write appropriate accessor and mutator methods.
Also, write a program that creates three instances/objects of the class. One
instance should hold your information, and the other two should hold your
friends’ or family members’ information.
Info.py
#Model class
class Person:
def __init__(self, name, address, age, phone_number):
self.__name = name
self.__address = address
self.__age = age
self.__phone_number = phone_number
def get_name(self):
return self.__name
def get_address(self):
return self.__address
def get_age(self):
return self.__age
def get_phone_number(self):
return self.__phone_number
#Person_Tester.py
#View Class/Program
import Info
def main():
# Create three instances/objects of Person Class
my_info = Info.Person('John Doe', '111 My Street', \
22, '555-555-1281')
mom_info = Info.Person('Mom', '222 Any Street', \
52, '555-555-1234')
sister_info = Info.Person('Jane Doe', '333 Her Street', \
20, '555-555-4444')
print('My information:')
display_info(my_info)
print()
print("Mom's information:")
display_info(mom_info)
print()
print("Sis's infomation:")
display_info(sister_info)
def display_info(info):
print('Name: ', info.get_name ())
print('Address: ', info.get_address())
print('Age: ', info.get_age())
print('Phone Number: ', info.get_phone_number())
class Customer(Person):
def __init__(self, name, address,age, phone_number, cust_number, on_list):
# Call superclass __init__ method
Person.__init__(self, name, address, age, phone_number)
def get_on_list(self):
return self.__on_list
# Customer_Tester.py
#View class/Program
import Info
def main():
# Local variables
name = ''
address = ''
age = 0
phone_number = ''
cust_number = 0
on_list_flag = False
if on_list == 'Yes':
on_list_flag = True
else:
on_list_flag = False
For the UML diagram for the Person Information System based on
Object Oriented MVC (Model View Controller) Design Pattern shown in
Figure 1, Design a Graphical User Interface for Customer View Class
shown in Figure 2.
Figure 1:UML for Person Information System Model class
#Model classes - Person class and its subclasses
###person.py###
# Person Class
class Person:
def __init__(self, name, address, phone_number):
self.__name = name
self.__address = address
self.__phone_number = phone_number
def get_name(self):
return self.__name
def get_address(self):
return self.__address
def get_phone_number(self):
return self.__phone_number
def __str__(self):
result = '\n========== '+\
'\nName: ' + self.get_name() + \
'\nAddress:'+ str(self.get_address()) + \
'\nPhone Number: ' + self.get_phone_number()
return result
class Customer(Person):
def __init__(self, name, address, phone_number, cust_number, on_list ):
Person.__init__(self, name, address, phone_number)
self.__cust_number = cust_number
self.__on_list = on_list
def get_on_list(self):
return self.__on_list
def __str__(self):
result= ""
result = (Person.__str__(self) + \
'\nCustomer Number: ' + self.get_cust_number() + \
'\nOn List: ' + self.get_on_list()+\
'\n==========')
return result
import person
import tkinter as tk
import os
class personGUI():
def __init__(self):
self.main_window = tk.Tk()
self.main_window.title("Person Information Display System")
self.info_text_area.insert("1.0", disp_string)
personGUI()
Week 9 Lab Challenge Activities
The challenge activities this week will help in working towards quiz 4.
Design a class that holds the Library Item Information, with item name, author,
publisher. Write appropriate accessor and mutator methods. Also, write a
tester program that creates three instances/objects of the Library Items class.