Trouble understanding with getting a unique instantiation in Python - python

I have an employee class which has an init method that reads an employees record in from a file. I also have an employees class which has an init_ method that attempts to read in all of the employee records.
I am having trouble with init for the employees class. Here is my code:
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
The print(emp) is there for error checking, it shows that the records are being read in properly. When the EOF is reached, the init method for the employee sets the id to 0 and the name of the employee to "". I have two problems:
After the loop, all of the employees in employees.records are the same - id 0 and blanks for names. I am assuming that that emp is not creating a new instance each time it is called, and so all of the employees are being set to that one instance of emp, the very last one from when EOF is reached.
I doubt my code is "Pythonesque"; suggestions for improvement are welcome.
P.S. database is globally defined to the file name.
The entire code is here, sorry about the length:
class employee:
count = 0
def __init__(self,f=None):
if (f==None): # a user is inputting the employee
self.lastname = input("Employees last name:")
while type(self.lastname)!=type("1"):
print("Your input needs to be a name\n")
self.lastname = input("Employees last name:")
self.firstname = input("Employees first name:")
while type(self.firstname)!=type("1"):
print("Your input needs to be a name\n")
self.firstname = input("Employees first name:")
self.payrate = float(input("Employees pay rate:"))
while type(self.payrate)!=type(0.0):
print("Your input needs to be a pay rate\n")
self.payrate = float(input("Employees pay rate:"))
employee.count = employee.count + 1
self.id = employee.count
else: # the employee is being read in from the database and f is a file pointer
# read in an employee record and return false for end of file.
checkEOF = f.readline().rstrip('\r\n') #check for end of file
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.id == other.id
return NotImplemented
def __str__(self):
return "Employee " + str(self.id) + " is "+self.firstname + " "+self.lastname+" and their pay rate is "+str(self.payrate)+"\n"
def __lt__(self, other):
if (self.lastname < other.lastname):
return True
elif (self.lastname > other.lastname):
return False
else: #same last names
if (self.firstname < other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: #same names
if (self.id < other.id):
return True
else: # note that ids cannot be the same
return False
def __gt__(self, other):
if (self.lastname > other.lastname):
return True
elif (self.lastname < other.lastname):
return False
else: # Same last names
if (self.firstname > other.firstname):
return True
elif (self.firstname > other.firstname):
return False
else: # Same names
if (self.id > other.id):
return True
else: # note that ids cannot be the same
return False
def payraise(self,payraise):
self.payrate = self.payrate+payraise
def saveemployee(self,fp):
fp.write(str(self.id)+"\n")
fp.write(self.firstname+"\n")
fp.write(self.lastname+"\n")
fp.write(str(self.payrate)+"\n")
class EmployeeList():
records=[]
def __init__(self):
with open(database) as fp:
emp=employee(fp)
while (emp.id > 0):
print(emp)
self.records.append(emp)
emp=employee(fp)
def __str__(self):
employeesprint = ""
for emp in self.records:
employeesprint = employeesprint + str(emp)
return employeesprint
def save(self):
self.records.sort()
with open(database,"w+") as fp:
fp.seek(0)
for emp in self.records:
emp.saveemployee(fp)
def menu():
print("\n")
print(choices[0]+". Add another employee")
print(choices[1]+". Print employees")
print(choices[len(choices)-1]+". Quit")
print("\n")
employees = EmployeeList()
choices = ["A","B","C"]
ch = "N"
while (ch != choices[len(choices)-1]):
menu()
ch=input("Make your choice ")
while not (ch in choices):
menu()
ch=input("Make your choice ")
if (ch == choices[0]):
employees.records.append(employee())
employees.save()
if (ch == choices[1]):
print(employees)
Sample output: You can see the two employees correctly being printed as they are read in:
Employee 1 is jane bob and their pay rate is 1.0
Employee 2 is jim bob and their pay rate is 3.4
A. Add another employee
B. Print employees
C. Quit
Make your choice B
Employee 0 is and their pay rate is 0.0
Employee 0 is and their pay rate is 0.0

your code:
if (checkEOF != ""):
employee.id = int(checkEOF)
employee.firstname = f.readline().rstrip('\r\n')
employee.lastname = f.readline().rstrip('\r\n')
employee.payrate = float(f.readline().rstrip('\r\n'))
else:
employee.id = 0
employee.firstname = " "
employee.lastname = " "
employee.payrate = 0.0
change 'employee' to 'self', 'employee' is the name of the class.

Related

Increase the first 15 digits of a 16 digit number by 1 within a range

Background
I am trying to ensure I am generating a unique credit card number. The credit card number needs to be 16 digits long with the last digit equal to the checksum which in this case is self.checksum = 1.
The first 6 digits of the credit card number must be 400000.
Since the last digit must be equal to the checksum or 1 in this case, I believe I need to implement a range in my code somehow to indicate when the maximum credit card number has been issued. In this case, the maximum credit card number is 40000009999999991. Anything after that would change the first 6 digits.
While the current solution "works" it does so by only adding 10 to the first possible credit card number initialized in the __init__ as self.credit_card_number = 4000000000000001.
Help needed
I am looking for help taking my existing code and implementing a range of some sort that can alert when the last credit card number in the range has been issued.
from random import randrange
class Accounts:
def __init__(self):
self.accounts_list = []
self.all_accounts = dict()
self.balance = 0
# Initial credit card number
self.credit_card_number = 4000000000000001
# Checksum is the last digit (16th) in the credit card number.
self.checksum = 1
# Pin number is generated in account_creation
self.pin = None
def main_menu(self):
while True:
main_menu_choice = input('1. Create an account\n'
'2. Log into account\n'
'0. Exit\n')
if main_menu_choice == '1':
self.account_creation()
def account_creation(self):
# Create credit card number ensuring it is unique by adding 1 to initialized value.
if len(self.accounts_list) == 0:
self.credit_card_number = self.credit_card_number
else:
self.credit_card_number = self.credit_card_number
self.credit_card_number = self.credit_card_number + 10
# Create pin number.
pin = int(format(randrange(0000, 9999), '04d'))
# Add credit card number to list used in the above if statement.
self.accounts_list.append(self.credit_card_number)
# Add the credit card number, pin, and balance to dictionary.
self.all_accounts[self.credit_card_number] = {'pin': pin, 'balance': self.balance}
# Print the output to make sure everything is OK.
print(self.accounts_list)
# Print the output to make sure everything is OK.
print(self.all_accounts)
print(f'\n'
f'Your card has been created\n'
f'Your card number:\n'
f'{self.credit_card_number}\n'
f'Your card PIN:\n'
f'{pin}'
f'\n')
Accounts().main_menu()
Can you update your init to generate credit cards:
def __init__(self):
# do you stuff
self.credit_card_first_6 = '400000'
self.checksum = '1'
# this will be used to create a unique credit card
self.count = 0
# middle numbers MUST be smaller than this
self.max_count = 1000000000
def account_creation(self):
#### do your stuff
# for this user they have a unique 9 digits in the middle
# this is then zero padded using zfill
unique_id = str(self.count).zfill(9)
# create the full credit card number
# note: store each bit as a str so we can concat then convert to int
credit_card_number = int(self.credit_card_first_6 + unique_id + checksum)
self.count += 1
# update your init values when your limit is reached
if self.count >= self.max_count:
self.count = 0
self.credit_card_first_6 = str(int(self.credit_card_first_6) + 1)
Since you marked Matt's answer as a valid I've added a quick refactor with some extra code that might be use full to you.
class Account:
balance = 0
__pin = None # this are
__number = None # private members
def __eq__(self, other):
return self.__number == other
def is_pin(self, pin):
return self.__pin == pin
def number(self):
return self.__number
# adding a 'is not none' makes
# it a 'write only once' variable,
# if a 'none' text is added as a input
# text is added not a None type
def set_pin(self, pin):
if self.__pin is None:
self.__pin = pin
return True
return False
def set_number(self, num):
if self.__number is None \
and len(str(num)) == 16:
self.__number = num
return True
return False
# eeextra simple checksum
def checksum(self):
ck_sum = 0
for i in str(self.__number):
ck_sum += int(i)
return int(str(ck_sum)[-1])
class Accounts:
base_num = 4000000000000000
def __init__(self):
self.accounts = []
self.num_offset = 0
#staticmethod
def dialog_choice():
choice = input(
'1. Create an account\n'
'2. Log into account\n'
'0. Exit \n \n'
)
return choice
def next_card_num(self):
self.num_offset += 1
return self.base_num + self.num_offset
def dialog_acount_creation(self):
card_pin = input('New pin ->')
card_num = self.next_card_num()
print('Card number ->', card_num)
return card_num, card_pin
#staticmethod
def dialog_login():
card_num = input('Card number ->')
card_pin = input('Card pin ->')
return int(card_num), card_pin
#staticmethod
def dialog_error(*args):
print('Error on acount', args[0])
def main_loop(self):
dia_map = {
'1': self.dialog_acount_creation,
'2': self.dialog_login,
}
cho_map = {
'1': self.account_creation,
'2': self.account_login,
}
err_map = {
'1': self.dialog_error,
'2': self.dialog_error,
}
while True:
o = self.dialog_choice()
if o == '0':
break
if o in cho_map:
q_dialog = dia_map[o]()
q_done = cho_map[o](*q_dialog)
if not q_done:
err_map[o](*q_dialog)
else:
print('Invalid option')
def account_login(self, num, pin):
for acc in self.accounts:
if acc == num and acc.is_pin(pin):
print('You are logged in !')
return True
return False
def account_creation(self, num, pin):
new_accaunt = Account()
new_accaunt.set_number(num)
new_accaunt.set_pin(pin)
self.accounts.append(new_accaunt)
return True
if __name__ == '__main__':
h_acc = Accounts()
h_acc.account_creation(4000000000000000, '1234')
h_acc.main_loop()

How to store the total withdrawn amount for each category obejct? [duplicate]

I have a Category class and there is a ledger attribute for each instance of this class. This ledger attribute is actually a list of dictionaries which contain the withdrawal and deposit amounts and descriptions in the form {"amount" : amount, "description" : description}. Now, I want to define a function create_spend_chart which will take a list of objects as the parameter, and will find the total amount of withdrawals. I have been able to do this successfully:
def create_spend_chart(categories):
total_withdrawn = 0
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
But the problem I'm facing here is, I can't seem to store the total withdrawal amount for each category object separately. How can I do this?
My code-base might help you ins answering the question:
class Category:
def __init__(self, name):
self.name = name
self.ledger = list()
def get_balance(self):
total_balance = 0
for i in self.ledger:
total_balance += i["amount"]
return total_balance
def check_funds(self, amount):
if self.get_balance() >= amount:
return True
else:
return False
def deposit(self, amount, description = "Deposit"):
form = {"amount" : int(amount), "description" : description}
self.ledger.append(form)
def withdraw(self, amount, description = "Withdrawal"):
if description == None:
description = "Withdrawal"
form = {"amount" : -int(amount), "description" : description}
if self.check_funds(amount):
self.ledger.append(form)
return True
else:
return False
def transfer(self, amount, category_object):
form1 = {"amount" : -int(amount), "description" : f"Transfer to {category_object.name}"}
form2 = {"amount" : int(amount), "description" : f"Transfer from {self.name}"}
if self.check_funds(amount):
self.ledger.append(form1)
category_object.ledger.append(form2)
return True
else:
return False
def __repr__(self):
Ledger = ""
for i in self.ledger:
if len(i["description"]) > 23:
des = i["description"][:23]
else:
des = i["description"]
Ledger += des.ljust(23) + str(round(i["amount"], 2)).rjust(7) + "\n"
Ledger = Ledger + "Total: " + str(round(self.get_balance(), 2))
receipt = f"{self.name}".center(30, "*") + "\n" + Ledger
return receipt
def create_spend_chart(categories):
total_withdrawn = 0
withdrawals = list()
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
total_withdrawn += -p["amount"]
PS: This function is not a method, it is defined outside of the class declaration.
Use a collections.defaultdict to make aggregations such as that easy as pie.
import collections
# ...
withdrawn_per_category = collections.defaultdict(int)
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] += -p["amount"]
(I've opted to use int as the default data type, but it doesn't truly matter here, so long as it's a conversible numeric type.)
Without collections
If for some reason you don't want to use the handy, built-in collections module, you can emulate the same behavior yourself with a regular dict:
withdrawn_per_category = {}
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] = withdrawn_per_category.get(i.name, 0) - p["amount"]

issues updating txt file in inventory program

I'm creating an invoice program that allows the user to select an item from a menu of products to either purchase or return. Once the user inputs the item ID and quantity desired, the program will read the inventory.txt file and write an UpdatedInventory.txt file, which will replace the inventory.txt file.
The inventory.txt file is formatted like this:
ID
item
stock
price
When my program runs, it does not print correctly on the UpdatedInventory.txt file. There's a lot of code here so bear with me.
As an aside, I feel like it would simplify the code if every purchase the user made was added into a list rather than hard coded. Thanks for the help!
Here's my main code:
import InventoryFile
import os
def readFile ():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines ()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
#create inventory object
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print ()
print ('Enter another item ID or 0 to stop')
def modify ():
found = False
search = -1
while search == -1:
search = input ('Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print ('The inventory has been updated...')
break
except Exception:
search = -1
print ('ERROR: Please enter a valid number.')
else:
inventoryFile = open ('inventory.txt', 'r')
temp_file = open ('UpdatedInventory.txt', 'w')
ID = str (inventoryFile.readline ())
while ID != '':
item = str (inventoryFile.readline ())
qty = float (inventoryFile.readline ())
price = float (inventoryFile.readline())
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
ID = ID.rstrip ('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float (input ('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase (purchaseEntry)
if purchase is False:
purchase = -1
print ('ERROR: Insufficient stock!')
new_qty = inventory_object.restock (purchase)
transaction_object = InventoryFile.TransactionItem (ID, item, new_qty, price)
transaction_object.set_id (ID)
transaction_object.set_name (item)
transaction_object.set_qty (new_qty)
transaction_object.set_price (price)
ID = transaction_object.get_id ()
item = transaction_object.get_name ()
qty = transaction_object.get_qty ()
price = transaction_object.get_price ()
temp_file.write (ID + '\n')
temp_file.write (item + '\n')
temp_file.write (str (qty) + '\n')
temp_file.write (str (price) + '\n')
found = True
else:
temp_file.write (ID + '\n' )
temp_file.write (item + '\n')
temp_file.write (str (new_qty) + '\n')
temp_file.write (str (price) + '\n')
ID = inventoryFile.readline ()
if found:
print ('The file has been updated.')
else:
print ('That item was not found in the file.')
inventoryFile.close ()
temp_file.close ()
os.remove ('inventory.txt')
os.rename ('UpdatedInventory.txt', 'inventory.txt')
print ('Inventory has been updated.')
break
return search
def main ():
all_items = readFile ()
printMenu (all_items)
modify ()
main ()
Here's my Inventory Class file:
class Inventory ():
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock += new_stock
return True
def purchase (self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print ('ERROR: Insufficient stock')
return False
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__ (self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id (self):
return self.__id
def set_id (self, new_id):
self.__id = new_id
def get_name (self):
return self.__name
def set_name (self, new_name):
self.__name = new_name
def get_qty (self):
return self.__qty
def set_qty (self, new_qty):
self.__qty = new_qty
def get_price (self):
return self.__price
def set_price (self, new_price):
self.__price = new_price
def calc_cost (self):
total = purch_qty * self.__price
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format (total, '7.2f')
Here is my inventory.txt file:
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
And here is what the updated inventory txt looks like after I input product ID 244, and purchase quantity of 5.
244
Large Cake Pan
4.0
19.99
576
Assorted Sprinkles
4.0
12.89
212
Deluxe Icing Set
4.0
37.97
827
Yellow Cake Mix
4.0
1.99
194
Cupcake Display Board
4.0
27.99
285
Bakery Boxes
4.0
8.59
736
Mixer
4.0
136.94
I've disabled TransactionItem. This seems to be working (I've combined the script files):
import os
class Inventory ():
def __init__(self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id(self):
return self.__id
def get_name(self):
return self.__name
def get_stock(self):
return self.__stock
def get_price(self):
return self.__price
def restock(self, new_stock):
if new_stock < 0:
print('ERROR')
return False
else:
self.__stock += new_stock
return True
def purchase(self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print('ERROR: Insufficient stock')
return False
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format(self.__stock, '7.2f') + format(self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__(self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id(self):
return self.__id
def set_id(self, new_id):
self.__id = new_id
def get_name(self):
return self.__name
def set_name(self, new_name):
self.__name = new_name
def get_qty(self):
return self.__qty
def set_qty(self, new_qty):
self.__qty = new_qty
def get_price(self):
return self.__price
def set_price(self, new_price):
self.__price = new_price
def calc_cost(self):
self.total = purch_qty * self.__price
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format(self.total, '7.2f')
def readFile():
# open the file and read the lines
inventoryFile = open('Inventory.txt', 'r')
raw_data = inventoryFile.readlines()
# remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip('\n')
clean_data.append(clean_item)
# read lists into objects
all_objects = []
for i in range(0, len(clean_data), 4):
ID = clean_data[i]
item = clean_data[i + 1]
qty = float(clean_data[i + 2])
price = float(clean_data[i + 3])
# create inventory object
inventory_object = Inventory(ID, item, qty, price)
all_objects.append(inventory_object)
return all_objects
def printMenu(all_data):
print()
print('Select an item ID to purchase or return: ')
print()
print('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print(item)
print()
print('Enter another item ID or 0 to stop')
def modify():
found = False
search = -1
while search == -1:
search = input(
'Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print('The inventory has been updated...')
break
except Exception:
search = -1
print('ERROR: Please enter a valid number.')
else:
inventoryFile = open('inventory.txt', 'r')
temp_file = open('UpdatedInventory.txt', 'w')
ID = str(inventoryFile.readline())
while ID != '':
item = str(inventoryFile.readline())
qty = float(inventoryFile.readline())
price = float(inventoryFile.readline())
inventory_object = Inventory(ID, item, qty, price)
ID = ID.rstrip('\n')
item = item.rstrip('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float(
input('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase(purchaseEntry)
if purchase is False:
purchase = -1
print('ERROR: Insufficient stock!')
#new_qty = inventory_object.restock(purchase)
#transaction_object = TransactionItem(
# ID, item, new_qty, price)
#transaction_object.set_id(ID)
#transaction_object.set_name(item)
#transaction_object.set_qty(new_qty)
#transaction_object.set_price(price)
#ID = transaction_object.get_id()
#item = transaction_object.get_name()
#qty = transaction_object.get_qty()
#price = transaction_object.get_price()
qty = inventory_object.get_stock()
price = inventory_object.get_price()
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
found = True
else:
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
ID = inventoryFile.readline()
if found:
print('The file has been updated.')
else:
print('That item was not found in the file.')
inventoryFile.close()
temp_file.close()
os.remove('inventory.txt')
os.rename('UpdatedInventory.txt', 'inventory.txt')
print('Inventory has been updated.')
break
return search
def main():
all_items = readFile()
printMenu(all_items)
modify()
main()
I hope it helps!
Have you tried stepping thru the program?
https://docs.python.org/2/library/pdb.html or https://docs.python.org/3/library/pdb.html
at some point you're losing information
(its hard to troubleshoot that big block of code sadly)

Python - passing a class through a function resulting in error

I have been programming a piece of code to try and carry through a class from one function to another (the code is also broken in other ways but those aren't the important ones). The major problem if you define a class in the enter function it then gives the error:
exec("""print({}.Show())""".format(x))
File "<string>", line 1, in <module>
NameError: name (whatever I have called the class title) is not defined
in the tr function.
import pickle
import traceback
import sys
classtitles = []
class Customer(object):
def __init__(self):
try:
self.load()
print(self.customer)
except:
None
def init2(self,customer_name,home_address,telephone_number):
self.customer = customer_name
self.address = home_address
self.phone = telephone_number
print(self.customer)
classtitles.append(self.customer)
def carpet_amounts(self, carpet_type, grippers_bool):
self.type = carpet_type
self.grippers = grippers_bool
def price(self, size, perimeter):
self.size = size
self.perimeter = perimeter
self.price = 0
if self.type == "First":
self.price = float(5.99) * self.size
if self.type == "Monarch":
self.price = float(7.99) * self.size
if self.type == "Royal":
self.price = int(60) * self.size
price_add = float(22.5) * self.size
if self.grippers == True:
price_add += self.perimeter * float(1.10)
hours = 0
while size >= 16:
hours += 1
size -= 16
self.hours = hours
price_add += hours * 65
self.price += price_add
def Show(self):
print("show")
if self.grippers == True:
grips = "with"
else:
grips = "without"
return ("the size is {}m^2 and with a {} undercarpet and {} grippers, totalling more than {} hours of work is {}".format(self.size,self.type,grips,self.hours,self.price))
def save(self):
"""save class as self.name.txt"""
file = open('ClassSave.txt','wb')
file.write(pickle.dumps(self.__dict__))
file.close()
def load(self):
"""try load self.name.txt"""
file = open('ClassSave.txt','r')
datapickle = file.read()
file.close()
self.__dict__ = pickle.loads(dataPickle)
def loadf():
f = open('classnames.txt','r')
mylist = f.read().splitlines()
for x in mylist:
exec("""{} = Customer()""".format(mylist[0]))
customs()
def customs():
try1 = input("Would you like to 1. Enter a new customer. 2. View all the customers. 3. Delete an old customer")
if try1 == '1':
enter()
elif try1 == 'q':
sys.exit()
else:
tr()
def enter():
name = input("What is thr customers name (no space i.e. 'JoeBloggs')? ")
address = input("What is their address")
phonenumber = str("What is their phone number")
exec("""{} = Customer()""".format(name))
exec("""{}.init2("{}","{}","{}")""".format(name,name,address,phonenumber))
print(classtitles)
carpet_type = input("What type of carpet would they like ('First','Monarch','Royal')? ")
grips = str(input("Would they like grips (1 = yes, 2 = no)? "))
if grips == '1':
grips = True
else:
grips = False
exec("""{}.carpet_amounts("{}",{})""".format(name,carpet_type,grips))
size = int(input("What is the m^2 size of their carpet? "))
perimeter = int(input("What is the m perimeter of their carpet? "))
exec("""{}.price({},{})""".format(name,size,perimeter))
exec("print({}.Show())".format(name))
file2 = open('classnames.txt','w')
for x in classtitles:
file2.write(x)
file2.close()
exec("{}.save()".format(name))
customs()
def tr():
x = input("name")
print(x)
exec("""print({}.Show())""".format(x))
customs()
loadf()

How to delete from an object

import pickle
class TasksError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Task(object):
def __init__(self, task = () ):
if task ==():
raise TasksError('Empty task.')
self.name = task[0]
self.date = task[1]
self.priority = task[2]
self.time = task[3]
self.type = task[4]
self.comment = task[5]
def __str__(self):
output = '''Name: %s
Date: %s
Priority: %s
Time: %s
Type: %s
Comment: %s
''' % ( self.name,
self.date,
self.priority,
self.time,
self.type,
self.comment)
return output
class Tasks(object):
def __init__(self, container = []):
self.container = [ Task(todo) for todo in container ]
def delete(self):
x = 0
for todo in self.container:
x = x + 1
print "Task Number",x,"\n", todo
delete = raw_input("what number task would you like to delete")
if delete == "y":
del todo
############
#x = 0
# for task in self.container:
# x = x+1
#print "Task Number",x,"\n", task
#delete = raw_input("what number task would you like to delete")
#if delete == "y":
#del(task)
def add(self, task):
if task == '':
raise TasksError('Empty task')
self.container.append( Task(task) )
def __str__(self):
output = '\n'.join( [ str(todo) for todo in self.container ] )
return output
if __name__== "__main__":
divider = '-' * 30 + '\n'
tasks = Tasks( container = [] ) # creates a new, empty task list
while True:
print divider, '''Make your selection:
1. Add new task
2. Print all tasks
3. Save tasks
4. Load tasks from disk
5. Find high priority tasks
6. Sort by date
7. Delete task
<ENTER> to quit
'''
try:
menu_choice = int(input("Select a number from the menu: "))
except:
print 'Goodbye!'
break
if menu_choice == 1:
task = raw_input (">>> Task: ")
date = raw_input (">>> Date as string YYYYMMDD: ")
priority = raw_input (">>> Priority: ")
time = raw_input (">>> Time: ")
Type = raw_input (">>> Type Of Task: ")
comment = raw_input (">>> Any Comments? ")
todo = (task, date, priority, time, Type, comment)
tasks.add( todo )
print tasks
elif menu_choice == 2:
print divider, 'Printing all tasks'
print tasks
elif menu_choice == 3:
print divider, 'Saving all tasks'
tasks.save()
elif menu_choice == 4:
print divider, 'Loading tasks from disk'
tasks.load()
elif menu_choice == 5:
print divider, 'Finding tasks by priority'
results = tasks.find_by_priority(priority='high')
for result in results: print result
elif menu_choice == 6:
print divider, 'Sorting by date'
tasks.sort_by_date()
print tasks
elif menu_choice == 7:
tasks.delete()
I have deleted parts of my code (hopefully nothing important).
Im having trouble getting python to delete my tasks once added.
Both methods defined as "def delete" give the error message type error: task/todo object does not support deletion.
Does anyone know a way around this?
You don't delete from list like that... Your code have 2 problems:
if you use for to loop through a iterable, you should not change it inside the loop.
to del from list you should use index.
Try this:
index = 0
while index < len(self.container):
delete = raw_input("what number task would you like to delete")
if delete == "y":
del self.container[index]
else:
index += 1

Categories