0% found this document useful (0 votes)
24 views20 pages

st1 Week 09 Tut Lab Solutions Updated

The document provides a tutorial and lab solutions focused on Python programming, specifically objects and classes. It includes examples of class definitions, error identification in code, and practical applications such as an Employee Wages Calculator and a Shopping Cart program. Additionally, it covers inheritance in class design and provides testing scenarios for various class implementations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views20 pages

st1 Week 09 Tut Lab Solutions Updated

The document provides a tutorial and lab solutions focused on Python programming, specifically objects and classes. It includes examples of class definitions, error identification in code, and practical applications such as an Employee Wages Calculator and a Shopping Cart program. Additionally, it covers inheritance in class design and provides testing scenarios for various class implementations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Week 09 Tutorial / Computer Lab Solutions

Objects and Classes in Python

 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

Triangle Class code Identify the error ?


class Triangle: The self parameter is missing
def __init(base, altitude): from the second line.
self.__base = base
self.__altitude = altitude

class Triangle: There should be a colon at the


def __init(self, base, altitude) end of the line beginning with
self.__base = base def.
self.__altitude = altitude
class Triangle() The pair of parentheses in the
def __init(self, base, altitude) first line should be replaced by
self.__base = base a colon.
self.__altitude = altitude Also, a colon should be placed
at the end of the second line.
class Triangle: Second line must be written as
def __init(self, base=1, altitude): def _ _init_ _(self,
self.__base = base altitude, base=1):.
self.__altitude = altitude Parameters that are passed to
by position must precede
those with default values.
class Triangle: No error
def __init(self,base, altitude):
self.__base = base
self.__altitude = altitude

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 setRadius(self, radius):


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 3.14


c=circle.Circle()
print(c.area())

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):

Bird is the superclass and Canary is the subclass

b. class Hammer(Tool):

Tool is the superclass and Hammer is the subclass

1. Write the first line of the definition for a Trout Class. The class should extend/inherit
the Fish Class.

class Trout(Fish):

2. Look at the following class definitions:

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()

I'm a piece of art.


I'm a painting.
3. Look at the following class definitions:

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?

Airplane is the superclass


JumboJet is the subclass

Is JumboJet an Airplane ? If yes, this is a valid Inheritance relationship

Jumbojet is superclass
Airplane is subclass

Is Airplane a jumbojet ? No !

 LABORATORY ACTIVITIES:

1. Object Oriented Employee Wages Calculator Program


Write a console program that requests a casual employee’s name, hours worked,
and hourly wages, and then calculates his or her week’s pay. The program should
contain a class named EmployeeWages with instance variables for a employee’s
name, hours worked, and hourly wages, and a method named payForWeek. The
Australian labour laws require that hourly employees be paid “time-and-a-half” for
working more than 40 hours in a week. A successful test run for the program should
be as shown below:

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 setName(self, name):


self.name = name

def getName(self):
return self.name

def setHours(self, hours):


self.hours = hours

def getHours(self):
return self.hours

def setWage(self, wage):


self.wage = wage

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()

# This is a employee wages program with no class (not object oriented)


def main():
print("===Non Object Oriented Employee Wages Calculator===")
name = input("Emter Employee's name: ")
hours = float(input("Emter number of hours worked: "))
wage = float(input("Emter hourly wage: "))
pay = payForWeek(hours, wage)
print("Pay for", name + ':', pay)

def payForWeek(hours,wage):
amount = hours * wage
if hours > 40:
amount = 40 * wage + ((hours - 40)*(1.5 * wage))
return "${0:,.2f}".format(amount)

main()

2. Object Oriented Shopping Cart Program

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 setDescription(self, description):


self.description = description

def getDescription(self):
return self.description

def setPrice(self, price):


self.price = price

def getPrice(self):
return self.price

def setQuantity(self, quantity):


self.quantity = quantity

def getQuantity(self):
return self.quantity

class Cart:
def __init__(self, items=[]):
self.items = items

def addItemToCart(self, item):


self.items.append(item)

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 setDescription(self, description):


self.description = description

def getDescription(self):
return self.description

def setPrice(self, price):


self.price = price

def getPrice(self):
return self.price

def setQuantity(self, quantity):


self.quantity = quantity

def getQuantity(self):
return self.quantity

ShoppingCart_Controller.py
class Cart:
def __init__(self, items=[]):
self.items = items

def addItemToCart(self, item):


self.items.append(item)

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 set_name(self, name):


self.__name = name

def set_address(self, address):


self.__address = address

def set_age(self, age):


self.__age = age

def set_phone_number(self, phone_number):


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())

# Call the main function.


main()

4. Extending Person Information Class


Person and Customer Classes: Write a class named Person with data attributes
for a person’s name, address, age and telephone number. Next, write a class
named Customer that is a subclass of the Person class. The Customer class
should have an additional data attribute for a customer number, and a Boolean
data attribute indicating whether the customer wishes to be on a mailing list.
Demonstrate Customer Class in a Tester Program with an object of Customer
class.

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)

# Initialize the cust_number and on_list attributes


self.__cust_number = cust_number
self.__on_list = on_list

# Mutator functions for cust_number and on_list


def set_cust_number(self, cust_number):
self.__cust_number = cust_number

def set_on_list(self, on_list):


self.__on_list = on_list

# Accessor functions for cust_number and on_list


def get_cust_number(self):
return self.__cust_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

# Get data attributes.


name = input('Enter the name: ')
address = input('Enter the address: ')
age = input('Enter the age: ')
phone_number = input('Enter the phone_number: ')
cust_number = input('Enter the customer number: ')
on_list = input('Does the customer wish to be ' \
'on the mailing list?(Yes/No) ')

if on_list == 'Yes':
on_list_flag = True
else:
on_list_flag = False

# Create an instance of Customer.


customer_1 = Info.Customer(name, address, age, phone_number, \
cust_number, on_list_flag)

# Display Customer Information.


print('Customer information: ')
print('Name:', customer_1.get_name())
print('Address:', customer_1.get_address())
print('Age:', customer_1.get_age())
print('Phone number:', customer_1.get_phone_number())
print('Customer Number:', customer_1.get_cust_number())
print('On Mailing List:', customer_1.get_on_list())
# Call the main function.
main()

5. GUI for the Person Information System

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

# The following methods are mutators for the


# class's data attributes.

def set_name(self, name):


self.__name = name

def set_address(self, address):


self.__address = address

def set_phone_number(self, phone_number):


self.__phone_number = phone_number

# The following methods are the accessors


# for the class's data attributes.

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

# Mutator functions for cust_number and on_list


def set_cust_number(self, cust_number):
self.__cust_number = cust_number
def set_on_list(self, on_list):
self.__on_list = on_list
# Accessor functions for cust_number and on_list
def get_cust_number(self):
return self.__cust_number

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")

# Set the container frames


self.name_frame = tk.Frame(self.main_window)
self.address_frame = tk.Frame(self.main_window)
self.phone_frame = tk.Frame(self.main_window)
self.customer_frame = tk.Frame(self.main_window)
self.on_list_frame = tk.Frame(self.main_window)
self.button_frame = tk.Frame(self.main_window)
self.info_frame = tk.Frame(self.main_window)

# Get person data.


# Create and pack the widgets for Person's name .
self.name_label = tk.Label(self.name_frame, text='Enter Name:')
self.name_entry = tk.Entry(self.name_frame, width=20)
self.name_label.pack(side='left')
self.name_entry.pack(side='left')

# Create and pack the widgets for Person's address .


self.address_label = tk.Label(self.address_frame, text='Enter Address:')
self.address_entry = tk.Entry(self.address_frame, width=20)
self.address_label.pack(side='left')
self.address_entry.pack(side='left')

# Create and pack the widgets for Person's phone .


self.phone_label = tk.Label(self.phone_frame, text='Enter Phone number:')
self.phone_entry = tk.Entry(self.phone_frame, width=20)
self.phone_label.pack(side='left')
self.phone_entry.pack(side='left')

# Create and pack the widgets for Person's Customer number .


self.customer_label = tk.Label(self.customer_frame, text='Enter Customer
number:')
self.customer_entry = tk.Entry(self.customer_frame, width=20)
self.customer_label.pack(side='left')
self.customer_entry.pack(side='left')

# Create and pack the widgets for On mailing list choice.


self.on_list_label = tk.Label(self.on_list_frame, text='Would you like to be on mailing
list:')
self.on_list_label.pack(side='left')
# Create and pack the widgets for on_list radio buttons
# the Radio buttons.
self.radio_var = tk.IntVar()
# Set the intVar object to 1.
self.radio_var.set(1)
self.rb1 =
tk.Radiobutton(self.on_list_frame,text='Yes',variable=self.radio_var,value=1)
self.rb2 = tk.Radiobutton(self.on_list_frame,text='No',variable=self.radio_var,
value=0)
# Pack the Radio buttons
self.rb1.pack()
self.rb2.pack()

# Create a display button and a Quit button.


self.display_button = tk.Button(self.button_frame, text='Display',
command=self.display_person_info)
self.quit_button = tk.Button(self.button_frame, text='Quit',
command=self.main_window.destroy)
# Pack the Buttons.
self.display_button.pack(side='left')
self.quit_button.pack(side='left')
# Create info display multiline text area
self.info_text_area = tk.Text(self.info_frame,bg ='light blue', height = 20,width =
40)
self.info_text_area.pack()

# Pack the frames.


self.name_frame.pack()
self.address_frame.pack()
self.phone_frame.pack()
self.customer_frame.pack()
self.on_list_frame.pack()
self.button_frame.pack()
self.info_frame.pack()
# Wait in the main loop until event handler click
tk.mainloop()

# event handler call back function (display person info button


def display_person_info(self):
# Get the person details from GUI and store them in variables.
name = (self.name_entry.get())
address = (self.address_entry.get())
phone = (self.phone_entry.get())
customer_num = (self.customer_entry.get())
on_list = (self.radio_var.get())
# Create an instance of person/Customer
customer_1 = person.Customer(name, address, phone, customer_num, on_list)

# Display the data that was entered.


self.info_text_area.delete("1.0", "end")
disp_string = ""
on_list = ""
disp_string += 'Here is the Person Information: '
disp_string += "\n-------------------------------"
disp_string += '\nPerson name: ' + customer_1.get_name()
disp_string += '\nAddress: ' + customer_1.get_address()
disp_string += '\nPhone number: ' + customer_1.get_phone_number()
disp_string += '\nCustomer number: ' + customer_1.get_cust_number()
if customer_1.get_on_list() == 1:
ol_flag = 'Yes'
else:
ol_flag = 'No'
disp_string += '\nMailing List: ' + ol_flag

self.info_text_area.insert("1.0", disp_string)

# end of display_person_info() event handler /call back method

personGUI()
Week 9 Lab Challenge Activities
The challenge activities this week will help in working towards quiz 4.

Challenge Activity 1: Library Information System Design and Testing

1. Library Item Class Design and Testing

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.

2. Extending Library Item Class


Library and Book Classes: Extend the Library Item class in (1) with a Book class
with data attributes for a book’s title, author, publisher and an additional
attributes as number of pages, and a Boolean data attribute indicating whether
there is both hard copy as well as eBook version of the book.
Demonstrate Book Class in a Tester Program with an object of Book class.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy