I'm writing a function that takes inputs in the form of code and returns a string.
class Item(object):
def __init__(self, code, name, stock, price):
self.code = code
self.name = name
self.stock = stock
self.price = price
beer = Item(124, "beer", 200, 12.90)
print(beer.code)
Is there any way to get the name "beer" from its code, 124. Like you could with a dictionary? dict = {124 : "beer"}
Assuming that first you had created a list of items, something like
items = []
items.append(Item(124, "beer", 200, 12.90)
items.append(Item(125, "diapers", 100, 5.90)
Then you could use a list comprehension to find items with a given code, e.g.
beer = [item for item in items if item.code==124][0]
This assumes you can guarantee there is only one item with code 124. You could even wrap this up in a function:
def find_item(code):
return [item for item in items if item.code==124][0]
You could create an Inventory class and do this:
class Item(object):
def __init__(self, code, name, stock, price):
self.code = code
self.name = name
self.stock = stock
self.price = price
def __repr__(self):
return '{}: {} - {} - {}'.format(self.code, self.name, self.stock, self.price)
class Inventory(object):
_inventory = {}
def find(self, code):
return self._inventory.get(code)
def add_item(self, code, name, stock, price):
if code in self._inventory:
raise KeyError('item with this code already present')
self._inventory[code] = Item(code, name, stock, price)
inventory = Inventory()
inventory.add_item(124, "beer", 200, 12.90)
inventory.add_item(125, "another beer", 400, 8.10)
search = inventory.find(124)
print search
print search.name
output:
124: beer - 200 - 12.9
beer
Related
I have recently starting coding and so far I only have about a month and a half of experience so I'm still learning. I am taking a stab at object oriented programming but I am trying to see where I can improve my code. For the purpose of this question, specifically the last method of code. As you can see in my where_to_watch_movie method, I have an instance in which I use append twice. I have read that repeating your code twice is a bad practice, so I am wondering if there is any other way to add these items to the list. I cannot use extend, but if there is no alternative way, I can also keep my double append as there will be no penalty for repeating myself. Still would like to know for my own best practices moving forward though if anyone knows!
class Movie:
"""Movie class that takes four data members"""
def __init__(self, title, genre, director, year):
self.title = title
self.genre = genre
self.director = director
self.year = year
def get_title(self):
"""get title of the movie"""
return self.title
def get_genre(self):
"""get genre of the move"""
return self.genre
def get_director(self):
""""get director of the movie"""
return self.director
def get_year(self):
""""get year of the movie"""
return self.year
'''class StreamingService:
def __init__(self, name):
"""streaming service class that takes two data members. THe catalog is a dictionary of movies with the titles
as keys and the movie objects as the corresponding values."""
self.name = name
self.catalog = dict()
def get_name(self):
"""returns name of the streaming service"""
return self.name
def get_catalog(self):
"""returns the catalog"""
return self.catalog
def add_movie(self, mov):
"""add movie to the catalog"""
self.catalog[mov.get_title()] = mov
def delete_movie(self, title):
"""delete movie from the catalog"""
if title in self.catalog:
self.catalog.pop(title)
class StreamingGuide:
def __init__(self):
"""streaming guide"""
self.StreamingServices = []
def add_streaming_service(self, streamingservice):
"""add streaming service to the streaming services list"""
self.StreamingServices.append(streamingservice)
def delete_streaming_service(self, streamingservicename):
"""remove streaming service from the streaming services list"""
if streamingservicename in self.StreamingServices:
self.StreamingServices.remove(streamingservicename)
def where_to_watch_movie(self, title):
"""returns a list that contains the name of the movie and year, as well as the streaming service
where you can find that movie."""
list_1 = []
for item in self.StreamingServices:
if title in item.get_catalog():
list_1.append(item.get_catalog()[title].get_title() + " ("
+ str(item.get_catalog()[title].get_year()) + ")")
list_1.append(item.get_name())
if len(list_1) == 0:
return None
else:
return list_1
"""
movie_1 = Movie('The Seventh Seal', 'comedy', 'Ingmar Bergman', 1957)
movie_2 = Movie('Home Alone', 'tragedy', 'Chris Columbus', 1990)
movie_3 = Movie('Little Women', 'action thriller', 'Greta Gerwig', 2019)
movie_4 = Movie('Galaxy Quest', 'historical documents', 'Dean Parisot', 1999)
stream_serv_1 = StreamingService('Netflick')
stream_serv_1.add_movie(movie_2)
stream_serv_2 = StreamingService('Hula')
stream_serv_2.add_movie(movie_1)
stream_serv_2.add_movie(movie_4)
stream_serv_2.delete_movie('The Seventh Seal')
stream_serv_2.add_movie(movie_2)
stream_serv_3 = StreamingService('Dizzy+')
stream_serv_3.add_movie(movie_4)
stream_serv_3.add_movie(movie_3)
stream_serv_3.add_movie(movie_1)
stream_guide = StreamingGuide()
stream_guide.add_streaming_service(stream_serv_1)
stream_guide.add_streaming_service(stream_serv_2)
stream_guide.add_streaming_service(stream_serv_3)
stream_guide.delete_streaming_service('Hula')
search_results = stream_guide.where_to_watch_movie('Little Women')"""
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
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
I am studying for my final and this was a quiz question I missed. I need most of the help on the getTotal method. I need to loop through the list, find the price of each item, add the price to the total and return the total. I struggle with loops and I am not sure how to pull the second item out of a list.. [1] ?? I have tried many ways and am getting frustrated.
If there is anyone up that is willing to help me that would be great. I am still learning and am new at this so go easy on me, but I really want to learn it. It's probably not as hard as I make it out to be, but Ill be waiting for some input. Thank you!
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def getPrice(self):
return self.price
def getName(self):
return self.name
class Cart:
def __init__(self, list):
self.list = []
def addItem(self, item):
self.list.append(self.list)
def getTotal(self):
total = 0
for item in self.list:
name, price = item # or price = item[1]
total = total + price
def getNumItems(self):
count = 0
for c in range(self.list):
count = self.list + 1
return count
def removeItem(self, item)
#removes the item from the cart's item list
def main():
item1 = Item("Banana", .69)
item2 = Item("Eggs", 2.39)
item3 = Item("Donut", .99)
c = Cart()
c.addItem(item1)
c.addItem(item2)
c.addItem(item3)
print "You have %i items in your cart for a total of $%.02f" %(c.getNumItems(), c.getTotal())
c.removeItem(item3)
print "You have %i items in your cart for a total of $%.02f" % (c.getNumItems(), c.getTotal())
main()
Here gives the time and I changed the code and now it is fully functional shopping cart
class Item(object):
def __init__(self, unq_id, name, price, qty):
self.unq_id = unq_id
self.product_name = name
self.price = price
self.qty = qty
class Cart(object):
def __init__(self):
self.content = dict()
def update(self, item):
if item.unq_id not in self.content:
self.content.update({item.unq_id: item})
return
for k, v in self.content.get(item.unq_id).iteritems():
if k == 'unq_id':
continue
elif k == 'qty':
total_qty = v.qty + item.qty
if total_qty:
v.qty = total_qty
continue
self.remove_item(k)
else:
v[k] = item[k]
def get_total(self):
return sum([v.price * v.qty for _, v in self.content.iteritems()])
def get_num_items(self):
return sum([v.qty for _, v in self.content.iteritems()])
def remove_item(self, key):
self.content.pop(key)
if __name__ == '__main__':
item1 = Item(1, "Banana", 1., 1)
item2 = Item(2, "Eggs", 1., 2)
item3 = Item(3, "Donut", 1., 5)
cart = Cart()
cart.update(item1)
cart.update(item2)
cart.update(item3)
print "You have %i items in your cart for a total of $%.02f" % (cart.get_num_items(), cart.get_total())
cart.remove_item(1)
print "You have %i items in your cart for a total of $%.02f" % (cart.get_num_items(), cart.get_total())
And a output is:
You have 8 items in your cart for a total of $8.00
You have 7 items in your cart for a total of $7.00
for getTotal:
def getTotal(self):
total = 0
for item in self.list:
name, price = item # or price = item[1]
total = total + price
BTW, Your addItem and getNumItems method are also wrong. Since it is final, you should try to understand what you are working on.