How do append an instance of a class? - python

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

Related

I am unsure why global variable won't update when accessed in class

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 a beginner in python.Need help in using collection

I want to create a function that create car object and adds to its collection of cars
cars={}
def add_car(model, price):
Is this the kind of thing you are looking for?
Option 1: If you meant object in the general sense.
cars={}
def add_car(model, price):
cars[model] = price
add_car("Subaru Forester",22000 )
print(cars)
Output: {'Subaru Forester': 22000}
This line cars[model] = price is how you add cars to the dict.
Option 2: If by object you mean a Python object.
class car:
def __init__(self, model, price):
self.model = model
self.price = price
cars={}
def add_car(model, price):
cars[model] = car(model, price)
add_car("Subaru Forester",22000 )
print(cars)
Output: {'Subaru Forester': <__main__.car object at 0x00D1E9F0>}
cars = []
class car:
def __init__(self, model, prize):
self.model = model
self.prize = prize
def add_car(model, price):
c = car(model, price)
cars.append(c)
add_car("Opel Astra", 22000 )
print(cars)

How do you add 2 inputs from an argument together?

I have made this code and now I want to add from the class 'Product' the price together. So I have 2 products: Computer and Nintendo and I want to add the price together, can I make a definition for this so that from product 3 and 4 it will also add up?
I hope my question makes sense, I'm a beginner in programming.
class Customer:
def __init__(self, ID, name, address):
self.ID = ID
self.name = name
self.address = address
def customer_information(self):
print('ID: '+ self.ID + ', Name: ' + self.name + ', Address: '+ self.address)
class Product:
def __init__(self, product_name, product_ID, price):
self.product_name = product_name
self.product_ID = product_ID
self.price = price
def product_information(self):
print(self.product_name+', '+self.product_ID + ', €'+str(self.price))
class Order:
def __init__(self):
self.customer = []
self.product = []
def add1(self, product):
self.product.append(product)
def customer_data(self, customer):
self.customer.append(customer)
def show(self):
for c in self.customer:
c.customer_information()
print('This order contains:')
for p in self.product:
p.product_information()
customer1 = Customer('542541', 'Name', 'Rotterdam')
customer2 = Customer('445412', 'Name', 'Schiedam')
product1 = Product('Computer', '34456', 200.00)
product2 = Product('Nintendo', '12345', 14.99)
product3 = Product('Camera', '51254', 50.00)
product4 = Product('Go-pro', '51251', 215.00)
myOrder = Order()
myOrder.customer_data(customer1)
myOrder.add1(product1)
myOrder.add1(product2)
myOrder1 = Order()
myOrder1.customer_data(customer2)
myOrder1.add1(product3)
myOrder1.add1(product4)
myOrder.show()
myOrder1.show()
Seems like you want to get the sum of all the product prices, or order totals. Both are the same result, but you have two classes that contain the same information so you can calculate the sums by either Product or Order:
productsum = product1.price + product2.price + product3.price + product4.price
ordersum = sum([p.price for p in myOrder.product]) + sum([p.price for p in myOrder1.product])
print(productsum) # 479.99
print(ordersum) # 479.99
Either way you'll get the same answer, just choose how you want to implement it.
Yes, you can create another variable in class order like-
def __init__(self):
self.customer = []
self.product = []
self.total = 0
and add every product's price to the total whenever a product is added to the list-
def add1(self, product):
self.product.append(product)
self.total += product.price

Python test andela

HST2: OBJECT ORIENTED PROGRAMMING LAB
Create a class called ShoppingCart.
Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.
Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.
Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly.
If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed.
Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough".
Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100.
Make sure Shop inherits from ShoppingCart.
In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.
# OOP Lab
class ShoppingCart(object):
def __init__(self):
total = 0
item = {}
self.total = total
self.item = item
def add_item(item_name, quantity, price):
cost = quantity * price
self.total += cost
self.item = {"item_name":quantity}
def remove_item(item_name,quantity,price):
cost = quantity * cost
self.total -= cost
for i in self.item:
if quantity > self.item[i]:
del self.item["item_name"]
def checkout(cash_paid):
if cash_paid < self.total:
return "Cash paid not enough"
class Shop(ShoppingCart):
def __init__(self):
quantity = 100
self.quantity = quantity
def remove_item():
self.quantity -= 1
#! Error State the following:
my add_item is having four argument instead of three each time i run this code:
Please i need help with this code, am new with python, i will appreciate any programming angel in python to rescue me now.
Try this, it should work out just fine:
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.total += quantity * price
if type(item_name) == str and quantity > 0:
self.items.update({item_name: quantity})
def remove_item(self, item_name, quantity, price):
if quantity >= self.items[item_name] and quantity >= 1:
items_cost = price * self.items[item_name]
self.total -= items_cost
del self.items[item_name]
else:
self.total -= quantity * price
self.items[item_name] -= quantity
def checkout(self, cash_paid):
balance = 0
if cash_paid < self.total:
return "Cash paid not enough"
balance = cash_paid - self.total
return balance
class Shop(ShoppingCart):
def __init__(self):
self.quantity = 100
def remove_item(self):
self.quantity -= 1
Class methods should accept self as the first argument so for example
def add_item(self, item_name, quantity, price):
Instead of
def add_item(item_name, quantity, price):
The "4th argument" being passed is implicitly self, that is why the number of arguments is one higher than you are expecting.

Trouble with removing items from list

I'm having trouble getting this function to work. The purpose of it is to delete items from a list.
def sell(inventory_list):
print()
count = int(input('How many items would you like to sell? '))
print()
for count in range(count):
print()
type = input('Enter the type of item you wish to sell? ')
print()
name = input('Enter the name of the item you wish to sell? ')
print()
price = float(input('What is the price of the item you wish to sell? $'))
items = Plant.SubPlant(type, name, price)
inventory_list.remove(items)
return inventory_list
Your inventory list doesn't have the new instance you are trying to remove. Just because it contains the same atrrs/values does not mean they are the same.
To be able to do this perhaps implement method __eq__ in your SubPlant class:
class SubPlant(object):
def __init__(self, type, name, price):
self.type = type
self.name = name
self.price = price
def __eq__(self, other):
return self.__dict__ == other.__dict__

Categories

Resources