I am new to Classes and hope someone can help me out. I am writing av program where a user can add cars to an existing list of cars. The code I have so far is below. I am probably doing several mistakes here, but the error message I get now is "NameError: name 'car' is not defined". I think I am using the Car Class / Vehicle Class wrong. Anybody got any ideas how I can get on track with this?
class Vehicle:
def __init__(self, Make, Model, Year, Mileage, Price):
self.Makename = Make
self.Modelname = Model
self.Yearr = Year
self.Mileagenw = Mileage
self.Pricenw = Price
def getValus(self):
return self.Makename + " " + self.Modelname+ " " + self.Yearr+" " + self.Mileagenw+" " + self.Pricenw
def Display(self):
print("Invetory Unit: Car \n Make: "+ self.Makename + "\n Model: " + self.Modelname+ "\n Year " + self.Yearr+"\n Miles " + self.Mileagenw+" \n Price :" + self.Pricenw)
class Car(Vehicle):
def __init__(self, Make, Model,Year,Mileage,Price,numofdoors):
Vehicle.__init__(self,Make, Model,Year,Mileage,Price)
self.numofdoorsnw = numofdoors
def GetCar(self):
return self.getValus() + ", " + self.numofdoorsnw
def Display(self):
print("Invetory Unit: Car \n Make: "+ self.Makename + "\n Model: " + self.Modelname+ "\n Year " + self.Yearr+"\n Miles " + self.Mileagenw+" \n Price :" + self.Pricenw+" \n Number of doors :" + self.numofdoorsnw)
def main():
vehicles_list = []
vehicles_list += [Car("Tesla", "S", "2020", "170000", "33000.0", "4")]
vehicles_list += [Car("Tesla", "X", "2021", "180000", "23000.0", "4")]
newCar = "Y"
while newCar == "Y":
print('Input car data')
Make = input('Merke: ')
Model = input('Model: ')
Year = input('Year: ')
Milage = input('Milage: ')
Price = input('Price: ')
numofdoors = input('Number of Doors: ')
vehicles_list += [Car(Make, Model, Year, Milage, Price, numofdoors)]
newCar = input('Add another car? (Y/N) ')
print(car.getValus())
main()
class Vehicle:
def __init__(self, Make, Model, Year, Mileage, Price):
# are you making names unique here? if so, they are in a different namespace so don't have to be different
self.Makename = Make
self.Modelname = Model
self.Yearr = Year
self.Mileagenw = Mileage
self.Pricenw = Price
def getValus(self):
return self.Makename + " " + self.Modelname+ " " + self.Yearr+" " + self.Mileagenw+" " + self.Pricenw
def Display(self):
print("Invetory Unit: Car \n Make: "+ self.Makename + "\n Model: " + self.Modelname+ "\n Year " + self.Yearr+"\n Miles " + self.Mileagenw+" \n Price :" + self.Pricenw)
class Car(Vehicle):
def __init__(self, Make, Model,Year,Mileage,Price,numofdoors):
Vehicle.__init__(self,Make, Model,Year,Mileage,Price)
self.numofdoorsnw = numofdoors
def GetCar(self):
return self.getValus() + ", " + self.numofdoorsnw
def Display(self):
print("Invetory Unit: Car \n Make: "+ self.Makename + "\n Model: " + self.Modelname+ "\n Year " + self.Yearr+"\n Miles " + self.Mileagenw+" \n Price :" + self.Pricenw+" \n Number of doors :" + self.numofdoorsnw)
def main():
# adding unnamed instances of the class Car to a list. Each Car object is an element of the list
vehicles_list = []
vehicles_list += [Car("Tesla", "S", "2020", "170000", "33000.0", "4")]
vehicles_list += [Car("Tesla", "X", "2021", "180000", "23000.0", "4")]
newCar = "Y"
while newCar == "Y":
print('Input car data')
Make = input('Merke: ')
Model = input('Model: ')
Year = input('Year: ')
Milage = input('Milage: ')
Price = input('Price: ')
numofdoors = input('Number of Doors: ')
vehicles_list += [Car(Make, Model, Year, Milage, Price, numofdoors)]
newCar = input('Add another car? (Y/N) ')
print(car.getValus()) # car is undefined. print the vehicles_list instead, it contains all Car objects you have made.
main()
Improved version:
class Vehicle:
def __init__(self, make, model, year, mileage, price):
self.make = make
self.model = model
self.year = year
self.mileage = mileage
self.price = price
def getValues(self):
return self.make + " " + self.model + " " + self.year + " " + self.mileage + " " + self.price
def Display(self):
print("Invetory Unit: Car \n Make: " + self.make + "\n Model: " + self.model + "\n Year " + self.year + "\n Miles " + self.mileage + " \n Price :" + self.price)
class Car(Vehicle):
def __init__(self, Make, Model,Year,Mileage,Price,num_doors):
Vehicle.__init__(self,Make, Model,Year,Mileage,Price)
self.num_doors = num_doors
def GetCar(self):
return self.getValues() + ", " + self.num_doors
def Display(self):
print("Invetory Unit: Car \n Make: "+ self.make + "\n Model: " + self.model+ "\n Year " + self.year + "\n Miles " + self.mileage +" \n Price :" + self.price + " \n Number of doors :" + self.num_doors)
def main():
vehicles_list = []
vehicles_list.append(Car("Tesla", "S", "2020", "170000", "33000.0", "4"))
vehicles_list.append(Car("Tesla", "X", "2021", "180000", "23000.0", "4"))
newCar = "Y"
while newCar == "Y":
print('Input car data')
Make = input('Make: ')
Model = input('Model: ')
Year = input('Year: ')
Milage = input('Milage: ')
Price = input('Price: ')
numofdoors = input('Number of Doors: ')
vehicles_list.append(Car(Make, Model, Year, Milage, Price, numofdoors))
newCar = input('Add another car? (Y/N) ')
for car in vehicles_list:
print(car.GetCar())
main()
result:
Input car data
Make: VW
Model: Golf
Year: 2020
Milage: 10000
Price: 20000
Number of Doors: 5
Add another car? (Y/N) n
Tesla S 2020 170000 33000.0, 4
Tesla X 2021 180000 23000.0, 4
VW Golf 2020 10000 20000, 5
On the point about class namespaces, there is a great talk from Raymond Hettinger explaining those : https://www.youtube.com/watch?v=8moWQ1561FY
On print(car.getValus()), you want to get values from an object of class Car called car but you never defined this object. You probably want to modify your main in the following way
def main():
vehicles_list = []
vehicles_list += [Car("Tesla", "S", "2020", "170000", "33000.0", "4")]
vehicles_list += [Car("Tesla", "X", "2021", "180000", "23000.0", "4")]
newCar = "Y"
while newCar == "Y":
print('Input car data')
Make = input('Merke: ')
Model = input('Model: ')
Year = input('Year: ')
Milage = input('Milage: ')
Price = input('Price: ')
numofdoors = input('Number of Doors: ')
input_car = Car(Make, Model, Year, Milage, Price, numofdoors)
vehicles_list += [input_car]
newCar = input('Add another car? (Y/N) ')
for car in veichles_list:
print(car.getValus())
Related
from datetime import datetime
from datetime import date
import datetime
import time
import math
seconds_Yearly = 3656060*24
seconds_Daily = 606024
seconds_Hourly = 60*60
minute = 60
eventName1 = input("What is the name of the first event?")
print(" ")
eventName2 = input("What is the name of the second event?")
print(" ")
event_Year1 = input("Which year is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Month1 = input("Which month [1-12] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Day1 = input("Which day [1-31] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Year2 = input("Which year is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Month2 = input("Which month [1-12] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Day2 = input("Which day [1-31] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Year1 = int(event_Year1)
event_Month1 = int(event_Month1)
event_Day1 = int(event_Day1)
event_Year2 = int(event_Year2)
event_Month2 = int(event_Month2)
event_Day2 = int(event_Day2)
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
event1_date = event1_dates.strptime((event_Year1), (event_Month1), (event_Day1), "d/m/Y")
print(str(event1_date))
print(" ")
event2_date = date((event_Year2), (event_Month2), event_Day2)
print(event2_date)
print(" ")
seconds_event1 = time.mktime(event1_date.timetuple())
print(seconds_event1)
print(" ")
seconds_event2 = time.mktime(event2_date.timetuple())
print(seconds_event2)
print(" ")
seconds_difference_rough = seconds_event2 - seconds_event1
seconds_difference = abs(seconds_difference_rough)
print(seconds_difference)
print(" ")
minutes_difference = seconds_difference/60
print(minutes_difference)
print(" ")
hours_difference = minutes_difference/60
print(hours_difference)
print(" ")
days_difference_rough = hours_difference/24
days_difference = abs(days_difference_rough)
print(days_difference)
print(" ")
years_difference_roughs = seconds_difference/seconds_Yearly
years_difference_rough = seconds_difference//seconds_Yearly
years_difference = abs(years_difference_rough)
years_difference_remainer = seconds_difference%seconds_Yearly
print(years_difference)
print(years_difference_roughs)
weeks_difference_parta = (days_difference/7)/52
weeks_difference_partb = weeks_difference_parta/years_difference_roughs
weeks_difference = abs(weeks_difference_partb)
print(weeks_difference)
months_difference_part1a = hours_difference/24/30.435
months_difference_part1aa = months_difference_part1a//1
months_difference_part1b = abs(months_difference_part1aa)
print(months_difference_part1b)
months_difference_part2a = (years_difference * 12) - months_difference_part1b
month_difference_roughs = (years_difference * 12) - months_difference_part1a
months_difference_part2b = abs(months_difference_part2a)
days_decimal, whole = math.modf(months_difference_part1a)
print(" ")
print(months_difference_part2b)
print(" ")
print(months_difference_part1a)
print(" ")
days_difference1a = days_difference/28
days_difference1ab = days_difference/30.45
days_difference1b = days_difference1ab//1
days_difference1c = (days_difference1a - days_difference1ab)
days_difference_total = abs(days_difference1b)
print(days_difference_total)
print(" ")
print(days_difference1ab)
week_difference = days_difference_total/7
week_difference_total = abs(week_difference)
print(week_difference_total)
print(" ")
#hours_one = hours_difference
def days ():
global days, days_remaing_negative, days_remaing_positve, days_remaing
if event_Year2 > event_Year1:
months_difference_rough = days_difference/(hours_difference/24/30.435)
months_difference = abs(days_difference_rough)
months_difference_remainer = seconds_difference%seconds_Daily
print(months_difference)
print(days_decimal)
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
days_remaing = abs(days_remaing)
print(days_remaing)
else:
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
print(days_remaing)
def weeks():
global days_remaing, days, new_week, new_days2
if days_remaing >= 7:
new_weeks = days_remaing/7
abs_new_week = abs(new_weeks)
new_week = new_weeks//1
new_week_decimal, whole = math.modf(abs_new_week)
new_days1 = new_week_decimal * 7
new_days2 = new_days1//1
print(new_week)
print(new_days2)
else:
new_week = 0
new_days2 = days_remaing
print(new_days2)
def difference():
global new_days2, new_week, months_difference_part1b, years_difference, eventName1, eventName2, days_remaing, days, new_week, months_difference_part2b
if event_Year2 > event_Year1 or event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("a")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("b")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 == event_Month1 and event_Day2 > event_Day1:
print("C")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
else:
print("D")
print(str(eventName1) + " " + "is" + " " + "on" + " " + str(event1_date) + " " + " " + "which is" + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "After" + " " + " " + str(eventName2))
days ()
weeks()
difference()
Are you trying to convert event1_dates?
from datetime import date
event_Year1=2020
event_Month1=1
event_Day1=30
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
print(event1_dates)
event1_date = event1_dates.strftime("%d/%m/%Y")
print(event1_date)
Output:
2020-01-30
30/01/2020
I can't get the data within each ticket object to print. What am I doing wrong? I've never used __dict__ beofre but do I need to? Output I am getting is
t1 = Ticket_1()
TypeError: __init__() missing 3 required positional arguments: 'Ticket_1', 'Ticket_2', and 'Ticket_3'
Code:
class Ticket: #creates ticket and makes a count of each ticket created
counter = 2000 # static field counter + 2000
counter += 1
ticket_number = counter
def __init__(self, Ticket_1, Ticket_2, Ticket_3):
self.Ticket_1 = Ticket_1()
self.Ticket_2 = Ticket_2()
self.Ticket_3 = Ticket_3()
class Ticket_1(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "martha"
staff_id = "MARTHAT"
email = "martha#whitecliffe.co.nz"
issue = "monitor is broken"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class Ticket_2(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "Not Specified"
staff_id = "PAULG"
email = "Not Specified"
issue = "need to change password"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class Ticket_3(Ticket):
def ticketVariables(self, creator_name, staff_id, email, issue):
creator_name = "Not Specified"
staff_id = "CARLH"
email = "carlhemmingway#whitecliffe.co.nz"
issue = "wifi isn't working"
ticket_list = []
ticket_list.append(ticket_number)
ticket_list.append(creator_name)
ticket_list.append(staff_id)
ticket_list.append(email)
ticket_list.append(issue)
def display(self):
print("Ticket Number: " + ticket_list[0])
print("Ticket Creator: " + ticket_list[1])
print("Staff ID: " + ticket_list[2])
print("Email Address: " + ticket_list[3])
print("Description: " + ticket_list[4])
class main:
t1 = Ticket_1()
t2 = Ticket_2()
t3 = Ticket_3()
myobj = Ticket(t1, t2, t3)
t1.display()
t2.display()
t3.display()
Clearly for now, I'm just trying to print the information within each ticket object, but also not sure if I should be using init to define those variables or not...?
The code below is supposed to output the following if you choose employee
Do you wish to enter data for an (E)mployee, a (S)alesperson, or would you like to (Q)uit?: e
Enter the name of the employee: (employee name)
Enter (employee name) hourly pay rate: (pay rate)
Enter (employee name) hours worked: (hours worked ```
Employee data:
Employee name: (employee name)
Employee hourly pay: (hourly pay)
Hours worked: (hours worked)
Pay: (pay)
That is if you choose the to enter data for an employee ^^^
Here is the following output if you would like the choose the following data for a Salesperson
Do you wish to enter data for an (E)mployee, a (S)alesperson, or would you like to (Q)uit?: s
Enter the name of the employee: (employee name)
Enter (employee name) hourly pay rate: (hourly pay)
Enter the number of hours worked by (employee name): (hours worked)
Enter the amount of sales made by (employee name): (sales made)
Enter the commission percentage that will be earned by (employee name): (commission percentage)
Salesperson data:
Employee name: (employee name)
Employee hourly pay: (hourly pay)
Hours worked: (hours worked)
Sales: (sales made)
Commission percentage: (commission percent)
Pay: (pay)
Here is the entire block of code that is executing all of this. Keep in mind that this has to be done using classes and polymorphism.
class Employee:
def __init__(self, hours_worked, hourly_rate):
self.__hours_worked = 0
self.__hourly_rate = 0
def set_hours_worked(self, hours_worked):
self.__hours_worked = hours_worked
def get_hours_worked(self):
return self.__hours_worked
def set_hourly_rate(self, hourly_rate):
self.__hourly_rate = hourly_rate
def get_hourly_rate(self):
return self.__hourly_rate
def calc_pay(self):
return self.__hourly_rate * self.__hours_worked
def __str_(self):
print()
string1 = 'Employee data: ' + '\n' + 'Employee name: ' + employee_name + '\n' + 'Employee hourly pay rate: ' + employee_pay + '\n' + 'Hours worked: ' + employee_hours + '\n' + 'Pay: ' + employee_pay
class Salesman(Employee):
def __init__(self, weekly_sales, commission, hours_worked, hourly_rate):
Employee.__init__(self, hours_worked, hourly_rate)
self.__weekly_sales = 0
self.__commission = 0
def set_weekly_sales(self, weekly_sales):
self.__weekly_sales = weekly_sales
def get_weekly_sales(self):
return self.__weekly_sales
def set_commission(self, commission):
self.__commission = commission
def get_commission(self):
return self.__commission
def calc_pay(self):
return Employee.calc_pay(self) + (self.__weekly_sales * self.__commission)
def __str__(self):
print()
string2 = 'Salesperson data: ' + '\n' + 'Employee name: ' + salesperson_name + '\n' + 'Employee hourly pay rate: ' + str(
salesperson_pay) + '\n' + 'Hours worked: ' + salesperson_hours + '\n' + 'Sales: ' + salesperson_sales + '\n' + 'Commission percentage: ' + str(
salesperson_commission) + '\n' + 'Pay: ' + str(salesperson_pay)
go_on = 'y'
while go_on == 'y':
input1 = input('Do you wish to enter data for an (E)mployee, a (S)alesperson, or would you like to (Q)uit?: ')
if input1 == 'e' or 'E':
employee_name = input('Enter the name of the employee: ')
employee_pay = input('Enter ' + employee_name + ' hourly pay rate: ')
employee_hours = input('Enter the number of hours worked by ' + employee_name + ': ')
employee_pay_rate = employee_pay * int(employee_hours)
employee = Employee(employee_name, employee_pay, employee_hours, employee_pay_rate)
print(employee)
if input1 == 's' or 'S':
salesperson_name = input('Enter the name of the employee: ')
salesperson_pay = float(input('Enter ' + salesperson_name + ' hourly pay rate: '))
salesperson_hours = input('Enter the number of hours worked by ' + salesperson_name + ': ')
salesperson_sales = input('Enter the amount of sales made by ' + salesperson_name + ': ')
salesperson_commission = float(input('Enter the commission percentage that will be earned by ' + salesperson_name + ': '))
salesperson = Salesman(salesperson_pay, salesperson_hours, salesperson_sales, salesperson_commission)
print(salesperson)
else:
go_on = 'n'
I am sure I got mostly everything right but I'm running into a couple problems and I don't know how to fix them.
Error: you are passing 5 arguments in the while loop to Employee with self included.
When taking input as a string from the user, use raw_input instead
of input.
input1 == "e" or "E" is always true. Do input1 == "e" or input1 == "E"
This way you are making use of the while loop to add as many users as needed.
And also some additional points:
You have a base class Employee whose constructor or init accepts (self, hours_worked, hourly_rate)
recommended: (self, name, hours_worked, hourly_rate)
In class Salesman's __init__ method, try to maintain the order of arguments passed where the parent class Employees arguments come first.
recommended: `class Salesman(Employee):
def __init__(self, name, hours_worked, hourly rate, weekly_sales, commission):
Employee.__init__(self, name, hours_worked, hourly_rate)
self.__weekly_sales = 0
self.__commission = 0`
class PersonalInfo:
def set_titles(self, title):
self.__titles = title
def set_names(self, name):
self.__names = name
def set_addresses(self, add):
self.__addresses = add
def set_ages(self, age):
self.__ages = age
def set_numbers(self, number):
self.__numbers = number
# Accessor methods
def get_titles(self):
return self.__titles
def get_names(self):
return self.__names
def get_addresses(self):
return self.__addresses
def get_ages(self):
return self.__ages
def get_numbers(self):
return self.__numbers
def main():
# references PersonalInfo object
info = PersonalInfo()
# stores values in the object
info.set_titles(input("Enter Mr, Mrs, Miss:"))
info.set_names(input("Enter full name:"))
info.set_addresses(input("Enter address:"))
info.set_ages(input("Enter age:"))
info.set_numbers(input("Enter number:"))
#displays values stored in object's fields
print("Name: " + info.get_titles() + " " + info.get_names() + "\n"
+"Address: " + info.get_addresses() + "\n"
+ "Birth: " + info.get_ages() + "\n"
+ "Number: " + info.get_numbers() + "\n")
main()
main()
I want this to be printed out 2 times since I have 2 users who will answer the questions, but I can't seem to understand how to save the input answers in a text file. Can someone please give me an example??:)
I'm such a noob at this
Change your main() to init(self): And call it twice if you need run it twice. You could write a method to output the data to a file instead of including it in init if you wanted to.
def __init__(self):
# stores values in the object
self.title = self.set_titles(input("Enter Mr, Mrs, Miss: "))
self.name = self.set_names(input("Enter full name: "))
self.age = self.set_ages(input("Enter age: "))
self.address = self.set_addresses(input("Enter address: "))
self.number = self.set_numbers(input("Enter number: "))
# displays values stored in object's fields
print("Name: " + self.get_titles() + " " + self.get_names() + "\n"
+"Address: " + self.get_addresses() + "\n"
+ "Birth: " + self.get_ages() + "\n"
+ "Number: " + self.get_numbers() + "\n")
# Appends data to file
outfile = open('data_from_user.txt','a')
outfile.write("Name: " + self.get_titles() + " " + self.get_names() + "\n")
outfile.write("Address: " + self.get_addresses() + "\n")
outfile.write("Birth: " + self.get_ages() + "\n")
outfile.write("Number: " + self.get_numbers() + "\n")
outfile.close()
person_1 = PersonalInfo()
person_2 = PersonalInfo()
# storing data inside string
string = 'NAME: {} \n Address: {} \n Birth: {} \n Number: {} \n'.format(info.get_titles(),info.get_names(),
info.get_addresses(),info.get_ages(),info.get_numbers())
# printing 2 times
print(string,string,sep='\n')
# writing in a file
x = open('filename','a')
x.write(string)
x.close()
I'm trying to write an object-oriented program that allows me to enter and store monthly income and bills, and view all data as needed. I can successfully store an object, but when I try to use my view_all function, I get this error:
in view_all print(item.get_month())
AttributeError: 'str' object has no attribute 'get_month'
If you could help me track down this problem I'd be grateful!
# Create a month class
class Month:
# Use __init__ method to initialize the attributes
def __init__(self, month, income, tds, pnm, zia, water):
self.__month = month
self.__income = income
self.__tds = tds
self.__pnm = pnm
self.__zia = zia
self.__water = water
# The set methods accept arguments:
def set_month(self, month):
self.__month = month
def set_income(self, income):
self.__income = income
def set_tds(self, tds):
self.__tds = tds
def set_pnm(self, pnm):
self.__pnm = pnm
def set_zia(self, zia):
self.__zia = zia
def set_water(self, water):
self.__water = water
# The get methods return the data:
def get_month(self):
return self.__month
def get_income(self):
return self.__income
def get_tds(self):
return self.__tds
def get_pnm(self):
return self.__pnm
def get_zia(self):
return self.__zia
def get_water(self):
return self.__water
# The __str__ method return's the object's state as a string
def __str__(self):
return "Month: " + self.__month + \
"\nIncome: " + self.__income + \
"\nTDS: " + self.__tds + \
"\nPNM: " + self.__PNM + \
"\nZia: " + self.__zia + \
"\nWater: " + self.__water
And the main program:
import Month_Class
import pickle
ADD_MONTH = 1
VIEW_ALL = 2
QUIT = 3
FILENAME = 'ruidoso.dat'
def main():
months = load_months()
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == ADD_MONTH:
add_month(months)
elif choice == VIEW_ALL:
view_all(months)
save_months(months)
def load_months():
try:
input_file = open(FILENAME, 'rb')
months_dct = pickle.load(input_file)
input_file.close
except IOError:
month_dct = {}
return month_dct
def get_menu_choice():
print()
print('Menu')
print('------------------')
print("1. Add data for a new month")
print("2. View data for all months")
print('Any other number saves and quits the program!')
print()
choice = int(input('Enter your choice: '))
while choice < ADD_MONTH or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def add_month(months):
month = input('Enter the name of the month: ')
income = input('Total income for this month: ')
tds = input('TDS Broadband bill total: ')
pnm = input('PNM bill total: ')
zia = input('Zia Natural Gas bill total: ')
water = input('City of Ruidoso bill total: ')
entry = Month_Class.Month(month, income, tds, pnm, zia, water)
if month not in months:
months[month] = entry
print('The entry has been added')
else:
print('That month already exists!')
def save_months(months):
output_file = open(FILENAME, 'wb')
pickle.dump(months, output_file)
output_file.close()
def view_all(months):
for item in months:
print(item.get_month())
print(item.get_income())
print(item.get_tds())
print(item.get_pnm())
print(item.get_zia())
print(item.get_water())
main()
You need to iterate over the dictionary differently
for month, item in months.items():
print(item.get_month())
...
In the view_all method, you must to iterate over dictionary:
for key, item in months.iteritems():
print(item.get_month())
and you got other error in __str__ method of Month class:
"\nPNM: " + self.__PNM + \
the correct is:
"\nPNM: " + self.__pnm + \