Introduction to OOP in Python

Here is a simple application that create a customer class and read/write to file.

This is for file named CustomerApp.py:

#Developed by Armin Nikdel
#Date: 11 Nov 2016
#License: GPLv3

#This class do evaluation and validations and keep customer
#and customer group data, method and functions

#Define constants
INVEST_TYPES=[‘fd’,’mf’,’ut’,’FD’,’MF’,’UT’]

#define Customer class
class Customer:

#define initialize function to create a new customer
def __init__(self,name,age,invest,inv_value):
#set value for customer object
self.setName(name)
self.setAge(age)
self.setInvest(invest)
self.setValue(inv_value)

#get name value
def getName(self):
return str(self.name)

#get age value
def getAge(self):
return int(self.age)

#get investment type
def getInvest(self):
return str(self.invest).lower()

#get full string of investment type
def get_invest_str(self):
if (str(self.invest).lower()==’fd’):
return “fixed deposit”

elif (str(self.invest).lower()==’mf’):
return “mutual fund”

elif (str(self.invest).lower()==’ut’):
return “unit trust”

return “unknown”
#get investment value
def getInvestVal(self):
return float(self.inv_value)

#set name value
def setName(self,value):
value=str(value)
if (value!=”):
#check if name is shorter or equal to 20
if (len(value)<=20):
self.name=value
return 1
else:
return 0
else:
return 0

#set age value
def setAge(self,value):
#try to get age value and make sure it is numerical
try:
#make sure age is not empty
#and it is in range
if str(value)!=” and \
int(value)>=18 and \
int(value) <=70:
self.age=value
return 1
else:
return 0
except:
#fail if string is given instead of number
return 0

#set investment type
def setInvest(self,value):
#check if it is valid type
if (str(value) in INVEST_TYPES):
self.invest=value
return 1
else:
self.invest=0
return 0

#set investment value
def setValue(self,value):
#try to make sure it is not string
try:
#if it is a positive value
#and it is not empty
if (str(value)!=” and float(value)>0):
self.inv_value=value
return 1
else:
return 0
except:
#if string given return 0 (false)
return 0
def balance(self):
if (self.getInvest()==’fd’):
# calculate Fixed Deposit investment
invest_rate=0.0315
elif (self.getInvest()==’mf’):
# calculate mutual fund investment
invest_rate=0.0654
elif (self.getInvest()==’ut’):
# calculate unit trust investment
invest_rate=0.0986
else:
invest_rate=0

if (invest_rate==0):
return 0
else:
#calculate investment balance
invest_balance=self.getInvestVal()+\
(self.getInvestVal()+
(self.getInvestVal()*
invest_rate*5))
return float(invest_balance)

#define equal function
def __eq__(self,other):
#make sure both side is customer object
try:
#make sure both side’s investment value match
return self.inv_value == other.getInvestVal()
except:
#one side is not customer object
return False

#define less than function
def __lt__(self, other):
return self.balance() > other.balance()

#define less or equal function
def __le__(self, other):
return self.balance() >= other.balance()

#define default string function for customer object
def __str__(self):
return(self.getName()+” “+str(self.getAge())
+” “+self.get_invest_str()+
” RM”+str(self.getInvestVal()))

#define customer group class
class CustomerGroup:
#customer group initializer function
def __init__(self,name):
self.setGroupName(name)
self.customerlist=[]

#function to get group name
def getGroupName(self):
return str(self.name)

#set group name
def setGroupName(self,name):
self.name=name
#add our customer object to object list
def addCustomer(self,cust):
self.customerlist.append(cust)
#return index number of customer
return (self.noOfCustomer()-1)
#return number of customers added to list
def noOfCustomer(self):
return len(self.customerlist)
#get total initial value of investments
def totalValue(self):
totalval=0
#go through list of customers
#and sum their investment
for c in self.customerlist:
val=c.getInvestVal()
totalval+=val
return totalval
#get list of customers by investment type
def findCustomerByType(self,type):
found=0
foundstr=””
#if requested type is valid
if str(type) in INVEST_TYPES:
#go through list of customers
for c in self.customerlist:
#see if customer’s investment type match
if str(type).lower()==c.getInvest():
found=found+1
if found==1:
foundstr=foundstr\
+”Customers with “\
+c.get_invest_str()+\
” investment:”
if foundstr!=””:
foundstr=foundstr+”\n”
#add to our string
foundstr=foundstr + c.getName()\
+ ” ” + str(c.getAge())\
+ ” RM” + str(c.balance())
if foundstr==””:
#if not found, return None
return None
else:
return(foundstr)

else:
return(“Investment Type is invalid. \
Please enter FD/MF/UT Only”)
#get total balance of customers
def findTotalBalance(self):
totalval = 0
#go through all customers and sum them
for c in self.customerlist:
val = c.balance()
totalval += val
return totalval

#get highest invested value customer
def highestValue(self):
maxval = 0
maxc = None
#go through list of customers
for c in self.customerlist:
#get balance
val = c.balance()
#if balance is bigger than previous
#then set current customer as highest
if val>maxval:
maxc=c
maxval=val
#if highest customer found return customer
if maxval>0:
return maxc
#if not found, return None
else:
return None
#remove customer from their index number
def customerWithdraw(self,index_no):
#check if index number is valid
if str(index_no)!=” and int(index_no)>=1\
and int(index_no)<=self.noOfCustomer():
#generate output string
output=(“Customer with Index ”
+ str(index_no) +
“:{“+str(self.customerlist[index_no-1])
+”} has been removed!”)
#remove customer form list
self.customerlist.pop(index_no-1)
return output
else:
return False
#save customers information to a txt file
def saveToFile(self,filename):
#create/overwrite file
output_file = open(filename+’.txt’, ‘w’)
#for each customer
for i in self.customerlist:
#insert customer values separated by comma
output_file.write(‘,’
.join(
(str(i.getName()),
str(i.getAge()),
str(i.getInvest()),
str(i.getInvestVal())))
)
#insert new line
output_file.write(‘\n’)
output_file.close()
return(‘File ‘+filename+
‘.txt saved successfully.’)
#load customer information from file
def loadFromFile(self,filename):
#load file
input_file = open(filename+’.txt’, ‘r’)
#get each line
for i in input_file:
#get customer values from each line
#separated by comma
input_name, \
input_age, \
input_invest, \
input_value = i.split(‘,’)
#create a customer object from received line
self.customerlist.append(
Customer(input_name,
input_age,
input_invest,
input_value))
return(‘File ‘ + filename +
‘.txt loaded successfully’)
#show list of customers
def listCustomers(self):
list=””
counter=0
if self.noOfCustomer()>0:
list=”All customers in this group:”
#loop through customers
for i in self.customerlist:
#and add them to string
list=list+”\n” + str(i)

return list
else:
return “No customer registered in this group”
#define equal function for CustomerGroup
#to check if group name is valid
#used for Menu #4 (Count customers in a group by name)
def __eq__(self,other):
return self.name==other

This is for file named CustomerDriver.py which have main() function in it:

#Developed by Armin Nikdel
#Date: 11 Nov 2016
#License: GPLv3

#This class control interaction between user and app.
#It receive input via command line and print output into shell.

#import our classes from CustomerApp.py file
from customerApp import *

#define our menu page
def menu():
print(“\nInvestment Scheme by Private Banking”)
print(“—————————–“+
“———————————“)
print(“1 Add a customer”)
print(“2 Display all customers”)
print(“3 Display total value of all investments”)
print(“4 List number of customer in a particular group”)
print(“5 Display customers with “+
“user-specified type of investment”)
print(“6 Display customer with the “+
“most balance in his/her account”)
print(“7 Remove customer, based on index”)
print(“8 Read customer information from file”)
print(“9 Write customer information to file”)
print(“0 Quit”)
#ask for user input
choice = input(“Your choice: “)
#return input value
return choice

#define our startup code
def main():
#set group name
group_name=””
#make sure to receive a non-empty name for group name
while group_name==””:
group_name=str(input(“Enter group’s name:”))
print(“”)
#create group
Group=CustomerGroup(group_name)

#show initial menu
choice = menu()

#loop until a exit string is presented
while (str(choice)!=’q’ and str(choice)!=’Q’
and str(choice)!=’0′ and str(choice)!=”):

#if selected Add a Customer:
if (choice==”1″):
#create an empty customer object first
customer_obj=Customer(0,0,0,0)
name_set=0
age_set=0
type_set=0
inv_set=0
#populate object by asking for name input
#and sending name input to customer class
#to validate it
while name_set==0:
name_set=customer_obj.setName(
str(input(“Customer Name? “)))
#if customer class return 0, it means
#it customer name is not valid, ask again
if name_set==0:
print(“Invalid Name. Please try again.”)
#ask for age until valid age is given
while age_set==0:
age_set=customer_obj.setAge(
str(input(“Customer age? “)))
if age_set==0:
print(“Invalid Age. Please try again.”)
print(“Age must be numerical and between 18 to 70”)
#ask for valid investment type until valid type is given
while type_set == 0:
type_set = customer_obj.setInvest(
str(input(“Investment Type(‘FD/MF/UT’)? “)))
if type_set == 0:
print(“Invalid type! Please enter again!”)
#ask for investment value until valid value is given
while inv_set == 0:
inv_set = customer_obj.setValue(
str(input(“Investment value? “)))
if inv_set == 0:
print(“Invalid value! Please enter again!”)
#once our customer object is populated with data
#add it to our group
Group.addCustomer(customer_obj)
print(“… Customer has been added successfully.”)

#if choice is display all customers
elif choice==”2″:
#display all customers
print(Group.listCustomers())
#if choice is display total value of all investments
elif choice == “3”:
#check if customers exists
if Group.noOfCustomer()>0:
#and print investment value and balance
print(“Total value of all investments is RM”
+ str(round(Group.totalValue(),2)) +
” and total balance of investment is RM”
+ str(round(Group.findTotalBalance(),2)))
else:
print(“No customer registered in this group”)
print()
#if choice is number of customers in a group
elif choice == “4”:
#get group name
gName=str(input(“Enter group name: “))
#check if group name match
if Group==gName:
#print count of customers in group
print(“Total customer in group ‘”+gName
+”‘: “+str(Group.noOfCustomer()))
else:
print(“Group not found.”)
#if choice is list of customers in specific investment type
elif choice == “5”:
type=str(input(“Type of investment (‘FD/MF/UT’): “))
#check if entered type is valid
if type in INVEST_TYPES:
#get customers in that type
customers=str(Group.findCustomerByType(
type.lower()))
#if value returned is not None, print list
if customers!=”None”:
print(customers)
else:
print(“No customer registered in this type”)
else:
print(“Type of Investment entered is Invalid”)
#if choice is customer with most balance in his/her account
elif choice == “6”:
#get largest customer from group
largest=Group.highestValue()
#if value is not None
if largest!=None:
#print customer along with his balance
print(“Customer with the highest balance:”)
print(str(largest) + ” RM”+ str(
round(largest.balance(),2)))
else:
print(“No customer registered in this group”)

#if choice is remove customer
elif choice==”7″:
#check if we have customers inside
if Group.noOfCustomer()>0:
#use try to make sure entered value is numerical
try:
#get customer index
cus_index=int(
input(“Which customer to withdraw? “))
#delete index customer
Delete=Group.customerWithdraw(cus_index)
#if delete successful announce it
if str(Delete)!=”False”:
print(Delete)
else:
print(“Invalid Index. Please try again”)
except:
#if string entered instead of number, show error
print(“You didn’t enter a valid numerical value”)

else:
print(“No customer registered in this group”)
#if choice is to load from file
elif choice == “8”:
filename = “”
#ask for filename
while filename == “”:
filename = str(
input(“Please enter filename to load from: “))
#try to load from file if file exists
#and if file format is correct
try:
print(Group.loadFromFile(filename))
#show error if file is not correct
except:
print(“Wrong file.”)
#if choice is save to file
elif choice == “9”:
#check if there is any customer in this group
if Group.noOfCustomer() > 0:
filename = “”
#ask for filename
while filename == “”:
filename = str(
input(“Please enter filename to save to: “))
#save to filename
print(Group.saveToFile(filename))
else:
print(“No customer registered in this group”)
else:
print(“Invalid Choice!”)
#show menu using while loop specified above
choice=menu()

#print exit/quit message
print(“\nThank you!”)

#run our main/startup code
main()

adminIntroduction to OOP in Python

Leave a Comment