Projects/MyProductClass Enhanced.py

80 lines
2.8 KiB
Python

import csv
class Product:
pay_rate = 0.8 # Class variable for a standard discount of 20%
all = []
def __init__(self, name, price, quantity):
assert price >= 0, f"Product price {price} is not greater than or equal to zero!"
assert quantity >= 0, f"Product quantity {quantity} is not greater than or equal to zero!"
self.name = name
self.price = price
self.quantity = quantity
# Action to execute
Product.all.append(self) # Store all instances in the class variable 'all'
def calculate_total_price(self):
return self.price * self.quantity
def apply_discount(self):
return self.calculate_total_price() * (self.pay_rate)
def __repr__(self):
return f"Product('{self.name}', {self.price}, {self.quantity})"
@classmethod
def instantiate_from_csv(cls):
with open('items.csv', 'r') as f:
reader = csv.DictReader(f)
items = list(reader)
for item in items:
try:
name = item.get('name')
price_str = item.get('price')
quantity_str = item.get('quantity')
if name is None or price_str is None or quantity_str is None:
raise ValueError(f"Missing data in row: {item}")
price = float(price_str)
quantity = int(quantity_str)
Product(name, price, quantity)
print(f"Created: {name}, ${price:.2f}, {quantity}")
except (TypeError, ValueError) as e:
print(f"Skipping row due to error: {item}{e}")
# Example usage:
if __name__ == "__main__":
Product.instantiate_from_csv() # Instantiate products from the CSV file
print("All Products", Product.all) # Print all instances stored in the class variable 'all'
'''
for instance in Product.all:
if instance.name in ["Smartphone", "Monitor", "Keyboard"]:
instance.pay_rate = 0.7 # Special discount of 30%
elif instance.name == "Tablet":
instance.pay_rate = 1.0 # No discount
else:
instance.pay_rate = 0.8 # Standard discount of 20%
total_price = instance.calculate_total_price()
discounted_price = instance.apply_discount()
print(f"Product: {instance.name}, Total Price: ${total_price:.2f}, Price after Discount: ${discounted_price:.2f}")
print(repr(instance)) # Print the formal representation of the instance
print(Product.all) # Print all instances stored in the class variable 'all'
'''