I am a beginner in python.Need help in using collection - python

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)

Related

Why do we pass arguments into a method instead of assigning them as attributes?

I am attempting to learn OOP in Python so I wanted to ask why do we pass parameters into the method when calling it, while the object is passed automatically by Python into the method as the first parameter and can be used to automatically identify and call its attributes instead of passing them when calling the method?
Why don't we do this:
class Item:
def calculate_total(self):
total = self.quantity * self.price
return total
item = Item()
item.price = 100
item.quantity = 5
item.calculate_total()
instead of this:
class Item:
def calculate_total(self, x, y):
total = x * y
return total
item = Item()
item.price = 100
item.quantity = 5
item.calculate_total(item.price, item.quantity)
The question is kinda flawed, as none of those should be seen in real-life code.
Attributes should be declared inside the class, preferrably at the moment of object initialisation.
class Item:
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
def calculate_total(self):
total = self.quantity * self.price
return total
item = Item(100, 5)
item.calculate_total()
This way we don't have a risk of self.price and self.quantity not being defined when we call calculate_total.
But, even with what you provided, why 2nd method would be worse quickly becomes apparent if you try to calculate things multiple times. Let's say you've got 3 slightly different totals (different currency maybe).
Would you rather write
item.calculate_total1(item.price, item.quantity)
item.calculate_total2(item.price, item.quantity)
item.calculate_total3(item.price, item.quantity)
or
item.calculate_total1()
item.calculate_total2()
item.calculate_total2()
?
As #Pranav Hosangadi mentions, if there are any parameters that do not have a place in the attributes of a class (e.g. discount, which can vary for different sales of the same item), that is where we would pass them to the method:
class Item:
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
def calculate_total(self, discount):
total = self.quantity * self.price * (1 - discount)
return total
item = Item(100, 5)
discount = 0.15
print(item.calculate_total(discount))

How do append an instance of a class?

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

Product Inventory program that takes products with an ID, quantity, and price and uses an Inventory class to keep track of the products

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.

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

Using classes to access information

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

Categories

Resources