Global variable will not update after I update the global variable within the function setProdID inside of the class Product. I add 1 to it, to make a new Product ID but it always stays at 0, then 1 gets added to it.
prodIDCounter = 0
class NameType:
def __init__(self, nameUse):
self.nameUse = nameUse
class Product:
def __init__(self, prodName, price):
self.prodName = prodName
self.price = price
def setProdName(self, newProdName):
self.prodName = newProdName
def setReview(self, review):
self.review = review
def setPrice(self, price):
self.price = price
#Whenever a new product is created, it gets a unique prodID, that increments by 1 each time
def setProdID():
global prodIDCounter
prodIDCounter += 1
return prodIDCounter
review = ""
prodID = setProdID()
class Audio(Product):
def __init__(self, prodName, price, NameType):
self.prodName = prodName
self.price = price
self.singer = NameType.nameUse
def setGenre(self, genre):
self.genre = genre
def printInfo(self):
print("[Music]")
print("Product ID: " + str(self.prodID) + " Product Name: " + self.prodName)
print("Price: $" + str(self.price) + " Product Review Rate: " + str(self.review))
print("Singer Name: " + self.singer)
print("Genre: " + self.genre + "\n")
genre = ""
class Cart:
def __init__(self, NameType):
self.owner = NameType.nameUse
def addItem(self, Product):
self.purchasedItems.append(Product.prodID)
def removeItem(self, prodIDRemove):
pass
def displayCart():
pass
MAX_ITEMS = 7
purchasedItems = []
#----------------------------------------------
#Create my cart here, Start of Main Test Driver
name1 = NameType("Bailey")
myCart = Cart(name1)
print(myCart.owner)
name1 = NameType("Music Artst")
music1 = Audio("Song Name", 5.50, name1)
music1.setReview(8.2)
music1.setGenre("Pop")
music1.printInfo()
name1 = NameType("Music Artist 2")
music2 = Audio("Song Name 2", 6, name1)
music2.setReview(7)
music2.setGenre("Punk")
music2.printInfo()
myCart.addItem(music1)
myCart.addItem(music2)
print(myCart.purchasedItems)
My code read out is:
Bailey
[Music]
Product ID: 1 Product Name: Song Name
Price: $5.5 Product Review Rate: 8.2
Singer Name: Music Artst
Genre: Pop
[Music]
Product ID: 1 Product Name: Song Name 2
Price: $6 Product Review Rate: 7
Singer Name: Music Artist 2
Genre: Punk
[1, 1]
I have tried multiple ways of doing it, but it never update the global variable and I am at a loss for what I should do. I keep geting the productID reading as 1 for all of the catalog entries. It adds the 1, but then forgets about it when prodIDCounter is called again when I make a new object.
I am looking to create a (very!) basic inventory management system
This is the brief:
Product Inventory Project - Create an application which manages an
inventory of products. Create a product class which has a price, id,
and quantity on hand. Then create an inventory class which keeps
track of various products and can sum up the inventory value.
Here is my code so far:
class Product:
def __init__(self, id_num, price, quantity):
self.price = price
self.id_num = id_num
self.quantity = quantity
class Inventory:
def __init__(self):
self.product_list = []
def add_item(self):
id_num = int(input('Enter id: '))
price = int(input('Enter price: '))
quantity = int(input('Enter quantity: '))
self.product_list.append(Product(id_num, price, quantity))
I don't understand how to make an instance of the product class append to the product list in testing. I feel like I am way off. Any help would be much appreciated!
The code is fine. You just need to execute :)
Look at this sample I just modified inputs and made static values for fast execution:
class Product:
def __init__(self, id_num, price, quantity):
self.price = price
self.id_num = id_num
self.quantity = quantity
class Inventory:
def __init__(self):
self.product_list = []
def add_item(self):
id_num = 1 #int(input('Enter id: '))
price = 100 #int(input('Enter price: '))
quantity = 4 #int(input('Enter quantity: '))
self.product_list.append(Product(id_num, price, quantity))
inv = Inventory()
inv.add_item()
print(inv.product_list[0].price)
You should get the print result of 100 which is the price of the item
The Product class seems to work fine but I'm trying to figure out how to get the Inventory class to separate each product into there specific categories. I feel like I'm close but whenever I try and print out the inventory it just shows where it's stored in memory and doesn't actually print anything out. The output i receive when running is at the bottom. I want it to print out the actual products and data, not the instance of it stored in memory.
class Product:
def __init__(self, pid, price, quantity):
self.pid = pid
self.price = price
self.quantity = quantity
def __str__(self):
#Return the strinf representing the product
return "Product ID: {}\t Price: {}\t Quantity: {}\n".format(self.pid, self.price, self.quantity)
def get_id(self):
#returns id
return self.pid
def get_price(self):
#returns price
return self.price
def get_quantity(self):
#returns quantity
return self.quantity
def increase_quantity(self):
self.quantity += 1
def decrease_quantity(self):
self.quantity -= 1
def get_value(self):
value = self.quantity * self.price
return 'value is {}'.format(value)
product_1 = Product('fishing', 20, 10)
product_2 = Product('apparel', 35, 20)
class Inventory:
def __init__(self, products):
self.products = products
self.fishing_list = []
self.apparel_list = []
self.value = 0
def __repr__(self):
return "Inventory(products: {}, fishing_list: {}, apparel_list: {}, value: {})".format(self.products, self.fishing_list, self.apparel_list, self.value)
def add_fishing(self):
for product in self.products:
if product.get_id() == 'fishing':
self.fishing_list.append(product)
return '{} is in the fishing section'.format(self.fishing_list)
def add_apparel(self):
for product in self.products:
if product.get_id() == 'apparel':
self.apparel_list.append(product)
return '{} is in the apparel section'.format(self.apparel_list)
inventory_1 = Inventory([product_1, product_2])
inventory_1.add_fishing()
print(inventory_1)
OUTPUT = Inventory(products: [<main.Product instance at 0x10dbc8248>, <main.Product instance at 0x10dbc8290>], fishing_list: [<main.Product instance at 0x10dbc8248>], apparel_list: [], value: 0)
You need to specify how an object of the class Inventory should be printed.
To do this you need to implement at least one of the following functions in your class.
__repr__
__str__
This answer helps, which of both you should use: https://stackoverflow.com/a/2626364/8411228
An implementation could look something like this:
class Inventory:
# your code ...
def __repr__(self):
return str(self.products) + str(self.fishing_list) + str(self.apparel_list) + str(self.value)
# or even better with formatting
def __repr__(self):
return f"Inventory(products: {self.products}, fishing_list: {self.fishing_list}, apparel_list: {self.apparel_list}, value: {self.value})
Note that I used in the second example f strings, to format the output string.
Im trying to write a simple vending machine.
I have Container class that contains items and class Items contains information like the prize and the amount.
The ID indentifies the item. Every calling add item will increment ID by one, so that every item is unique.
I would like to get the prize of given ID.
So for example: I add item, it has ID=30, I give ID and it returns the prize of it.
I tried something like this, but it does not work:
from Item import Item
class Container:
id = 30
def __init__(self, objects=None):
if objects is None:
objects = {}
self.objects = objects
def add_object(self, obj: Item):
self.objects.update({id: obj})
Container.id = container.id + 1
def get_length(self):
return len(self.objects)
def find_price_of_given_id(self, id):
# return self.objects.get(id).get_price()
pass
Cola = Item(20)
print(Cola.get_amount())
container = Container()
container.add_object(Cola)
print(container.objects.items())
Item class:
class Item:
def __init__(self, price,amount=5):
self.amount = amount
self.price = price
def get_price(self):
return self.price
def get_amount(self):
return self.amount
I dont know why also print(container.objects.items()) returns dict_items([(<built-in function id>, <Item.Item object at 0x00000000022C8358>)]), why not ID = 30 + Item object
id is the name of a builtin method. Don't use it as a variable name - leads to name confusion.
You're assigning the id inside the container class but never giving it back, so that people can look up the item using the id.
In python3, dict.items returns a dict_items iterator, so you need to iterate over it to get to the items within.
class Item:
def __init__(self, price, amount=5):
self.amount = amount
self.price = price
def get_price(self):
return self.price
def get_amount(self):
return self.amount
def __str__(self):
return f"{self.amount} # {self.price}"
class Container:
item_id = 30
def __init__(self, objects=None):
if objects is None:
objects = {}
self.objects = objects
def add_object(self, obj: Item):
id_to_assign = Container.item_id
self.objects.update({id_to_assign: obj})
Container.item_id = Container.item_id + 1
return id_to_assign
def get_length(self):
return len(self.objects)
def find_price_of_given_id(self, item_id):
return self.objects.get(item_id).get_price()
Cola = Item(20)
print(Cola.get_amount())
container = Container()
cola_id = container.add_object(Cola)
print(container.objects.items())
print(container.find_price_of_given_id(cola_id))
Output:
5
dict_items([(30, <__main__.Item object at 0x104444b00>)])
20
this is my product class
class Product(object):
def __init__(self,price,name,catalognum,starRating):
self.price = price
self.name = name
self.catalognum = catalognum
self.starRating = starRating
def __str__():
print "Catalognum:[0]\n\
Name: [1]\n\
Price: $[2]\n\
Rating: [3]".format(catalognum,name,price,num_starRating)
def num_starRating(self):
return "*"*int(self.rating)
class Book(object):
def __init__(self,price,name,catalognum,starRating,author,ISBN,publisher):
self.price = price
self.name = name
self.catalognum = catalognum
self.starRating = starRating
self.author = author
self.ISBN = ISBN
self.publisher = publisher
def __str__():
print "author:[0]\n\
Title:[1]\n\
Price:$[2]\n\
ISBN:[3]\n\
Publisher:[4]\n\
Rating[5]".format(author,Title,Price,ISBN,num_starRating)
class Movie(object):
def __init__(self,Director,Studio,Title,Price,Running_Time,starRating,name,catalognum):
self.Director = Director
self.Studio = Studio
self.Title = Title
self.Price = Price
self.Running_Time = Running_Time
self.starRating = starRating
self.name = name
self.catalognum = catalognum
def __str__():
print "Director:[0]\n\
Title:[1]\n\
Price:[2]\n\
Running_Time:[3]min\n\
Studio:[4]\n\
Rating[5]".format(Director,Title,Price,Running_Time,Studio,num_starRating)
This is my catalog class
class Catalog(object):
def __init__(self,product_file):
self.product_file = product_file
sortByColumn = 0
self.cataloglist = self.BuildCatalogList
def BuildCatalogList(self):
file = open(self.product_file,"r")
filelist = file.readlines()
product_list = []
for i in range(1,len(file_list)):
product = filelist[i].split(',')
item = product(float(product[2]),int(product[3]),product[1],product[0])
product_list.append(item)
return product_list
def setsortby(self,sortype):
self.sortbycolumn = sorttype
def printcatalogtable(self):
print “[0][1][2][3]”.format(“catalog #”,”name”,”price($)”,”rating”)
import os
directory = os.listdir(“.”)
for filename in directory:
if filename [:-3:] == “pyc”:
os.remove(filename)
catalog = catalog(“bookdata.txt)
for printcatalogtable
print”[0:20]][1:25][2:15][3]”.format(“catalog #”,”name”,”price($)”,”rating)
for product in cataloglist:
print “(0:20)(1:25)(2:15.2f) (3)”[3]”.format(product,catalognum,product,name,price,name,product,price,product.getstarrating())
Using two classes, I tried to print out my file i have saved in format that follows catalog class
but its not working out, any ideas?
It should work out like this:
Catalog Number (6 digits),Title,Price,Star Rating (1-5),Author First Name,Author Last Name,ISBN,Publisher
123456,Game of Thrones: A Song of Ice and Fire,11.99,5,George RR,Martin,9780553582017,Random House Publishing Group
654321,City of Bones,11.99,4,Cassandra,Clare,9781406331400,Margaret K McElderry Books
654613,How I Met My Husband,14.99,4,Alice,Munro,2354365435123,Book Bublishers Inc
524638,The Hunger Games,9.99,4,Susan,Collins,9780439023481,Scholastic Press
632356,Lives of the Saints,19.99,2,Ninno,Ricci,8883336666,Harol Hitch Hijackers Books
675031,1984,11.99,5,George,Orwell,1782127755,Secker and Warburg London
111111,Forbidden City,5.99,1,William,Bell,4435-13422453,Lamest Books Corp
315644,Harry Potter and the Prisoner of Azkaban,14.99,5,JK,Rowling,64569-7861-0537,Raincoast
478931,Fifty Shades of Grey,2.99,0,EL,James,783844-6512-982,BooksBooksBooks Inc.
101010,Breaking Dawn,0.99,1,Stephanie,Meyer,101010-1010-101,LOLOLOLOL Press
548573,The Great Gatsby,14.99,4,F Scott,Fitzgerald,9781597226769,Scribners
123827,Steve Jobs,39.99,4.5,Walter,Isaacson,9781451648539,Google Inc
453123,Twilight,0.1,1,Stephenie,Meyer,9781594133299,Simons Inc.
445234,A Midsummer Night's Dream,10.99,3,William,Shakespeare,123455-4322-144,Penguin Group
542324,Paper Town,12.99,2,John,Green,698773-3122-341,Penguin Group
991337,Shutter Island,19.99,4.5,Dennis,Lehane,1234567890154,Awesome Group
123431,The Magic School Bus at the Waterworks,50,5,Joanna ,Cole,0-590-40360-5,Scholastic Corporation
Your BuildCatalogList starts at 0 spaces this should be changed as below (and of course for all the other functions that belong to the class Catalog.
class Catalog(object):
def __init__(self,product_file):
self.product_file = product_file
sortByColumn = 0
self.cataloglist = self.BuildCatalogList
# Spaces added to this function.
def BuildCatalogList(self):
file = open(self.product_file,"r")
filelist = file.readlines()
product_list = []
for i in range(1,len(file_list)):
product = filelist[i].split(',')
item = product(float(product[2]),int(product[3]),product[1],product[0])
product_list.append(item)
return product_list
The indentation of __init__ and __str__ methods of Book and Movie classes are wrong. Indent it properly.