is it possible to access to an external class method from a loop into a dictionary?
Here 2 examples, one access by a loop into a list and the other one by a dictionary. The first one does the job I'd like to reach with the dictionary (the second one):
ins.py
class Ins:
def __init__(self, cognome, nome, indirizzo, entrate, spese):
self.__cognome = cognome
self.__nome = nome
self.__indirizzo = indirizzo
self.__entrate = entrate
self.__spese = spese
def get_cognome(self):
return self.__cognome
def get_nome(self):
return self.__nome
def get_indirizzo(self):
return self.__indirizzo
def get_totale(self):
return str(float(self.__entrate) - float(self.__spese))
def __str__(self):
return "Cognome: " + self.__cognome + "\nNome: " + self.__nome + \
"\nIndirizzo: " + self.__indirizzo +\
"\nEntrate: " + self.__entrate + "\nSpese: " + self.__spese
ins_main_list.py
import ins
dict = []
def main():
again = 'y'
while again.lower() == 'y':
cognome = input('Inserire Cognome: ')
nome = input('Inserire Nome: ')
indirizzo = input('Inserire Indirizzo: ')
entrate = input('Inserire Entrate: ')
spese = input('Inserire Spese: ')
again = input("Continuare con l'inserimento? (Y/N) ")
print()
entry = ins.Ins(cognome, nome, indirizzo, entrate, spese)
dict.append(entry)
for item in dict:
print(item)
print(item.get_totale())
print()
main()
ins_main_dict.py
import ins
dict = {}
def main():
again = 'y'
while again.lower() == 'y':
cognome = input('Inserire Cognome: ')
nome = input('Inserire Nome: ')
indirizzo = input('Inserire Indirizzo: ')
entrate = input('Inserire Entrate: ')
spese = input('Inserire Spese: ')
again = input("Continuare con l'inserimento? (Y/N) ")
print()
entry = ins.Ins(cognome, nome, indirizzo, entrate, spese)
dict[cognome] = entry
for item in dict:
print(dict[item])
print(item.get_totale())
print()
main()
As you can see in the last example item.get_totale() give me an attribute error. How is possible to access into it?
I believe you should be doing dict[item].get_totale(), not item.get_totale(). item is iterating over the keys of dict (which are strings), not your custom class
Related
My assignment requires 3 functions. The 1st takes several inputs and then returns a string. The 2nd and 3rd functions pull information from the 1st and return their own strings. The problem I'm having is that when I call the 2nd and 3rd functions in the main(), I'm being prompted for the inputs in the 1st function again. Otherwise, the 2nd and 3rd functions eventually produce the output I'm looking for.
I'm somewhat limited in how I can approach writing the functions due to the assignment criteria, so apologies if it's a bit roundabout. I'm pretty sure I'm missing the forest for the trees here, any help would be greatly appreciated!
def get_book_info():
input_book_title = str(input("enter book title: "))
format_title = input_book_title.strip()
format_title = format_title.title()
input_book_isbn = str(input("enter book ISBN: "))
format_isbn = input_book_isbn.strip()
input_author_name = str(input("enter author name: "))
format_author = input_author_name.strip()
format_author = format_author.title()
input_publisher = str(input("Enter publisher: "))
format_publisher = input_publisher.strip()
format_publisher = format_publisher.title()
input_year_published = int(input("enter year published: "))
input_price = float(input("enter book price: "))
info = f"{format_title}/{format_isbn}/{format_author}/{format_publisher}/{input_year_published}/{input_price:.2f}"
return info
def to_csv_format():
book_info_string = get_book_info()
book_csv = book_info_string.replace("/", ", ")
return book_csv
def to_json_format():
book_info_string = get_book_info()
# find title
separator = book_info_string.find("/")
json_title = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find ISBN
separator = book_info_string.find("/")
json_isbn = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find author
separator = book_info_string.find("/")
json_author = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find publisher
separator = book_info_string.find("/")
json_publisher = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find year published
separator = book_info_string.find("/")
json_year = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find price
json_price = book_info_string
book_json = f'"title":"{json_title}","isbn":"{json_isbn}",author_name":"{json_author}","publisher":"{json_publisher}","year_published:":"{json_year}","price":"{json_price}"'
return book_json
def main():
get_book_info()
print("----------------")
book_csv = to_csv_format()
print(book_csv)
print("----------------")
book_json = to_json_format()
print(book_json)
pass
main()
Every time you call get_book_info() you will prompted to enter your data. You have to call it only once in the main, store the result in a variable and pass this variable to your other functions.
def get_book_info():
input_book_title = str(input("enter book title: "))
format_title = input_book_title.strip()
format_title = format_title.title()
input_book_isbn = str(input("enter book ISBN: "))
format_isbn = input_book_isbn.strip()
input_author_name = str(input("enter author name: "))
format_author = input_author_name.strip()
format_author = format_author.title()
input_publisher = str(input("Enter publisher: "))
format_publisher = input_publisher.strip()
format_publisher = format_publisher.title()
input_year_published = int(input("enter year published: "))
input_price = float(input("enter book price: "))
info = f"{format_title}/{format_isbn}/{format_author}/{format_publisher}/{input_year_published}/{input_price:.2f}"
return info
def to_csv_format (book_info_string):
book_csv = book_info_string.replace("/", ", ")
return book_csv
def to_json_format (book_info_string):
# find title
separator = book_info_string.find("/")
json_title = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find ISBN
separator = book_info_string.find("/")
json_isbn = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find author
separator = book_info_string.find("/")
json_author = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find publisher
separator = book_info_string.find("/")
json_publisher = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find year published
separator = book_info_string.find("/")
json_year = book_info_string[0:separator]
book_info_string = book_info_string[separator + 1:]
# find price
json_price = book_info_string
book_json = f'"title":"{json_title}","isbn":"{json_isbn}",author_name":"{json_author}","publisher":"{json_publisher}","year_published:":"{json_year}","price":"{json_price}"'
return book_json
def main():
info = get_book_info()
print("----------------")
book_csv = to_csv_format (info)
print(book_csv)
print("----------------")
book_json = to_json_format (info)
print(book_json)
pass
main()
#bll
import pickle
import pandas as pd
class Customer:
cuslist=[]
def __repr__(self):
return(str(self))
def __init__(self):
self.id=0
self.age=0
self.name=0
self.dateofBirth = 0
self.address = 0
self.phoneNumber = 0
self.amount = 0
self.zipCode = 0
self.experience = 0
self.form = 0
def addcustomer(self):
Customer.cuslist.append(self)
def searchcustomer(self):
for e in Customer.cuslist:
if(e.id==self.id):
self.age=e.age
self.name=e.name
self.dateofBirth = e.dateofBirth
self.address = e.address
self.phoneNumber = e.phoneNumber
self.amount = e.amount
self.zipCode = e.zipCode
self.experience = e.experience
self.form = e.form
break
def deletecustomer(self):
for e in Customer.cuslist:
if (e.id == self.id):
Customer.cuslist.remove(e)
break
def updatecustomer(self):
for e in Customer.cuslist:
if(e.id==self.id):
e.age=self.age
e.name=self.name
e.dateofBirth = self.dateofBirth
e.address = self.address
e.phoneNumber = self.phoneNumber
e.amount = self.amount
e.zipCode = self.zipCode
e.experience = self.experience
e.form = self.form
break
#staticmethod
# def convertoExcel(self):
# df = pd.DataFrame(Customer.cuslist.self)
# writer = pd.ExcelWriter('pandas.xlsx', engine='xlsxwriter')
# df.to_excel(writer, sheet_name='Sheet1')
# writer.save()
#staticmethod
def savetoPickle():
f=open("D://cetpa//mypickle.txt","wb")
pickle.dump(Customer.cuslist,f)
f.close()
#staticmethod
def loadfromPickle():
f = open("D://cetpa//mypickle.txt", "rb")
Customer.cuslist=pickle.load(f)
f.close()
#pl
if (__name__ == "__main__"):
while(1):
print("Enter 1 to Add Customer")
print("Enter 2 to Search Customer")
print("Enter 3 to Delete Customer")
print("Enter 4 to Modify Customer")
print("Enter 5 to Display All Customer")
print("Enter 6 to Exit")
ch = input("Enter A Number: ")
if(ch=='1'):
cus=Customer()
cus.id=input("enter id: ")
cus.age = input("enter age: ")
cus.name = input("enter name: ")
cus.dateofBirth = input("enter date of birth: ")
cus.addcustomer()
print("Added Successfully!!")
elif(ch=="2"):
cus=Customer()
cus.id=input("Enter Customer ID: ")
cus.searchcustomer()
print("Customer ID: ",cus.id, "Customer Age: ", cus.age, "Customer Name: ",cus.name)
elif(ch=="3"):
cus=Customer()
cus.id=input("Enter Customer ID: ")
cus.deletecustomer()
print("Entry Deleted!!")
elif(ch=='4'):
cus=Customer()
cus.id=input("Enter Customer ID: ")
cus.age=input("Enter Updated Customer Age: ")
cus.name=input("Enter Updated Customer Name: ")
cus.updatecustomer()
print("Customer Updated Successfully!!")
elif(ch=='5'):
cus=Customer()
for e in Customer.cuslist:
print("Customer ID: ",e.id)
print("Customer Age",e.age)
print("Customer Name: ",e.name)
print("Customer Date of Birth: ",e.dateofBirth)
elif (ch == '6'):
Customer.savetoPickle()
elif (ch == '7'):
Customer.loadfromPickle()
elif (ch == '8'):
print(Customer.cuslist)
Look into openpyxl.
It's a python module that lets you do stuff like this:
from openpyxl import Workbook
book = Workbook()
sheet = book.active
sheet['A1'] = "name"
sheet['A2'] = customer1.name
sheet['A3'] = customer2.name
sheet['B1'] = "age"
sheet['B2'] = customer1.age
sheet['B3'] = customer2.age
book.save("my_excel_file.xlsx")
def warehouseInventoryCreationBios():
bios = []
warehouseName = ["\nWarehouse: WBS"]
bios.append(warehouseName)
warehouse_initial_quantity_aircondSec = 1000
aircondSec = ["Section: AS", "Parts: compressor", "Part ID: ABS01", "Initial Quantity in the warehouse:", warehouse_initial_quantity_aircondSec, '\n']
bios.append(aircondSec)
.
.
return bios
warehouseInventoryCreationBios()
def updateBiosWarehouseInventory():
bios = warehouseInventoryCreationBios()
warehouseUpdateSupplier = []
name = input('Enter Supplier name: ')
name = name.lower()
id_parts = input('The id of the part: ')
id_parts = id_parts.upper()
order_from_supplier = int(input('How many orders from supplier: '))
warehouseUpdateSupplier.append(name)
warehouseUpdateSupplier.append(id_parts)
warehouseUpdateSupplier.append(str(order_from_supplier))
if name == 'tab':
if id_parts == "ABS01" or id_parts == "TBS05" or id_parts == "BBS02":
if id_parts == "ABS01":
compressor_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return compressor_quantity_warehouse
.
.
return warehouseUpdateSupplier
updateBiosWarehouseInventory()
Input: Enter Supplier name: tab
The id of the part: abs01
How many orders from supplier: 100
Output: NameError: name 'warehouse_initial_quantity_aircondSec' is not defined
How can I add the value warehouse_initial_quantity_aircondSec in the first function with the warehouse_initial_quantity_aircondSec in the second function
Newbie here, sorry ><
You are trying to use a variable in the second function, which is defined in the first as a local variable, you should return that value to use it:
def warehouseInventoryCreationBios():
bios = []
warehouseName = ["\nWarehouse: WBS"]
bios.append(warehouseName)
warehouse_initial_quantity_aircondSec = 1000
aircondSec = ["Section: AS", "Parts: compressor", "Part ID: ABS01", "Initial Quantity in the warehouse:", warehouse_initial_quantity_aircondSec, '\n']
bios.append(aircondSec)
.
.
# return multiple values (as tuple)
return bios, warehouse_initial_quantity_aircondSec
warehouseInventoryCreationBios() # this line is unnecessary, only calculations with no results used after it
def updateBiosWarehouseInventory():
# receive multiple values
bios, warehouse_initial_quantity_aircondSec = warehouseInventoryCreationBios()
warehouseUpdateSupplier = []
name = input('Enter Supplier name: ')
name = name.lower()
id_parts = input('The id of the part: ')
id_parts = id_parts.upper()
order_from_supplier = int(input('How many orders from supplier: '))
warehouseUpdateSupplier.append(name)
warehouseUpdateSupplier.append(id_parts)
warehouseUpdateSupplier.append(str(order_from_supplier))
if name == 'tab':
if id_parts == "ABS01" or id_parts == "TBS05" or id_parts == "BBS02":
if id_parts == "ABS01":
compressor_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return compressor_quantity_warehouse
.
.
return warehouseUpdateSupplier
updateBiosWarehouseInventory()
I even used print statements to check if y.name and favourite were the same when checking this and they were yet it still wasn't entering the if statement when using
if y.name == favourite
or
if favourite ==y.name
I'm super confused as to why that is since I thought this was just a standard equality check (The beginning of the code is mostly set up, just included it for context in the case that there was a problem there and not the if statement). Thank you in advance!
class Anime(object):
name: str = ""
year_aired = 0
genre1: str = ""
def __init__(self, name, genre1, year_aired):
self.name = name
self.genre1 = genre1
self.year_aired = year_aired
def _make_anime(name, genre1, year_aired):
anime = Anime()
return anime
animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
if i.find("*") != -1:
animearr[numanime].genre1 = i
else:
k = Anime("","", 2018)
k.name = i
animearr.append(k)
numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
if y.name == favourite:
favgenre = y.genre1
print(favgenre)
I think you should add strip.("\n") before you compare two string.
class Anime(object):
name: str = ""
year_aired = 0
genre1: str = ""
def __init__(self, name, genre1, year_aired):
self.name = name
self.genre1 = genre1
self.year_aired = year_aired
def _make_anime(name, genre1, year_aired):
anime = Anime()
return anime
animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
if i.find("*") != -1:
animearr[numanime].genre1 = i
else:
k = Anime("","", 2018)
k.name = i
animearr.append(k)
numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
if y.name == favourite.strip("\n"):
favgenre = y.genre1
print(favgenre)
I have an intro class in Python where part of the instructions are:
(2) Build the ShoppingCart class with the following data attributes and related methods. Note: Some can be method stubs (empty methods) initially, to be completed in later steps.
Parameterized constructor which takes the customer name and date as parameters
Attributes
customer_name (string) - Initialized in default constructor to "none"
current_date (string) - Initialized in default constructor to "January 1, 2016"
cart_items (list)
Methods
add_item()
Adds an item to cart_items list. Has parameter ItemToPurchase. Does not return anything.
The code is:
class ItemToPurchase:
def __init__(self):
self._name = "none"
self._price = 0
self._quantity = 0
self._description = "none"
def item_name(self, name):
self._name = name
def item_price(self, price):
self._price = price
def item_quantity(self, quantity):
self._quantity = quantity
def item_description(self, description):
self._description = description
def __str__(self):
print("For item " + self._name + ": " + self._description + " there are " + str(self._quantity) + " available at $" + str(self._price) + ".")
def print_item_cost(self):
print(self._name + " " + str(self._quantity) + " # $" + str(self._price) + " = $" + str(self._quantity * self._price))
def print_item_description(self):
print(self._name + ": " + self._description)
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
cart_items = []
_customer_name = name
_current_date = date
def add_item(self, cartItem):
self.cart_items.append(cartItem)
def remove_item(self, item_name):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
if itm._name == item_name:
del self.cart_items[i]
count += 1
if count == 0:
print(" ")
print("Item not found in cart. Nothing removed.")
def modify_item(self, ItemToPurchase):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
if itm._name == ItemToPurchase._name:
count += 1
if ItemToPurchase._description != "none":
itm.item_description(ItemToPurchase._description)
if ItemToPurchase._price != 0:
itm.item_price(ItemToPurchase._price)
if ItemToPurchase._quantity != 0:
itm.item_quantity(ItemToPurchase._quantity)
if count == 0:
print(" ")
print("Item not found in cart. Nothing modified.")
def get_num_items_in_cart(self):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
count += itm._quantity
return count
def get_cost_of_cart(self):
cost = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
cost += (itm._quantity * itm._price)
return cost
def print_total(self):
print(self._customer_name + "'s Shopping Cart - " + self._current_date)
count = len(self.cart_items)
if count == 0:
print(" ")
print("SHOPPING CART IS EMPTY")
return 0
print("Number of Items: " + str(count))
print(" ")
for itm in self.cart_items:
itm.print_item_cost()
total = self.get_cost_of_cart()
print("Total: $" + str(total))
def print_descriptions(self):
print(self._customer_name + "'s Shopping Cart - " + self._current_date)
print(" ")
print("Item Descriptions")
for itm in self.cart_itmes:
print(itm.item_name() + ": " + itm.item_description())
def print_menu(cart):
print(" ")
print("MENU")
print("a - Add item to cart")
print("r - Remove item from cart")
print("c - Change item quntity")
print("i - Output items' descriptions")
print("o - Output shopping cart")
print("q - Quit")
print(" ")
def main():
#Define Constants and variables
custName = ""
dateToday = ""
custName = input("Enter customer's name: ")
dateToday = input("Enter today's date: ")
print("Customer name: " + custName)
print("Today's date: " + dateToday)
myCart = ShoppingCart(custName,dateToday)
option = ""
while option != "q":
print_menu(myCart)
option = input("Choose an option: ").lower().strip()
if option == "o":
myCart.print_descriptions()
elif option == "a":
print("ADD ITEM TO CART")
itemName = input("Enter the item name: ")
itemDescr = input("Enter the item description: ")
itemPrice = int(input("Enter the item price: "))
itemQuantity = int(input("Enter the item quantity: "))
print(" ")
cartItem = ItemToPurchase()
cartItem.item_name(itemName)
cartItem.item_description(itemDescr)
cartItem.item_price(itemPrice)
cartItem.item_quantity(itemQuantity)
myCart.add_item(cartItem)
elif option == "r":
print("REMOVE ITEM FROM CART")
itemName = input("Enter name of item to remove: ")
myCart.remove_item(itemName)
elif option == "c":
print("CHANGE ITEM QUNATITY")
itemName = input("Enter the item name: ")
itemQuantity = int(input("Enter the new quantity: "))
changeItem = ItemToPurchase(itemName)
changeItem.item_quantity(itemQuantity)
myCart.modify_item(changeItem)
main()
I am getting the following error:
Enter customer's name: Rog
Enter today's date: Oct 20
Customer name: Rog
Today's date: Oct 20
MENU
a - Add item to cart
r - Remove item from cart
c - Change item quntity
i - Output items' descriptions
o - Output shopping cart
q - Quit
Choose an option: a
ADD ITEM TO CART
Enter the item name: Sketchers
Enter the item description: Black
Enter the item price: 120
Enter the item quantity: 2
Traceback (most recent call last): File
"C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 176, in
main() File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 163, in main
myCart.add_item(cartItem) File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 44, in add_item
self.cart_items.append(cartItem) AttributeError: 'ShoppingCart' object has no attribute 'cart_items'
Can anyone tell me what I am doing incorrectly?
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
cart_items = []
_customer_name = name
_current_date = date
These are all local variable. If you want them to be attributes of the instance, you have to explicitly refer to self:
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
self.cart_items = []
self._customer_name = name
self._current_date = date