개발하자

Create a list of a class as an attribute of a second class in Python

Cuire 2023. 4. 15. 21:32
반응형

Create a list of a class as an attribute of a second class in Python

I have an intro class in Python where part of the instructions are:

(2) Build the ShoppingCart class with the following data attributes and related methods. Note: Some can be method stubs (empty methods) initially, to be completed in later steps.

  • Parameterized constructor which takes the customer name and date as parameters
  • Attributes
  • customer_name (string) - Initialized in default constructor to "none"
  • current_date (string) - Initialized in default constructor to "January 1, 2016"
  • cart_items (list)
  • Methods
  • add_item()

  • Adds an item to cart_items list. Has parameter ItemToPurchase. Does not return anything.

The code is:

    class ItemToPurchase:

    def __init__(self):
        self._name = "none"
        self._price = 0
        self._quantity = 0
        self._description = "none"

    def item_name(self, name):
        self._name = name

    def item_price(self, price):
        self._price = price

    def item_quantity(self, quantity):
        self._quantity = quantity

    def item_description(self, description):
        self._description = description

    def __str__(self):
        print("For item " + self._name + ": " + self._description + " there are " + str(self._quantity) + " available at $" + str(self._price) + ".")

    def print_item_cost(self):
        print(self._name + " " + str(self._quantity) + " @ $" + str(self._price) + " = $" + str(self._quantity * self._price))

    def print_item_description(self):
        print(self._name + ": " + self._description)    

class ShoppingCart:

    def __init__(self, name="none", date="January 1, 2016"):
        cart_items = []
        _customer_name = name
        _current_date = date

    def add_item(self, cartItem):
        self.cart_items.append(cartItem)

    def remove_item(self, item_name):
        count = 0
        itms = self.cart_items[:]
        for i in range(len(itms)):
            itm = itms[i]
            if itm._name == item_name:
                del self.cart_items[i]
                count += 1

        if count == 0:
            print(" ")
            print("Item not found in cart. Nothing removed.")

    def modify_item(self, ItemToPurchase):
        count = 0
        itms = self.cart_items[:]
        for i in range(len(itms)):
            itm = itms[i]
            if itm._name == ItemToPurchase._name:
                count += 1
                if ItemToPurchase._description != "none":
                    itm.item_description(ItemToPurchase._description)
                if ItemToPurchase._price != 0:
                    itm.item_price(ItemToPurchase._price)
                if ItemToPurchase._quantity != 0:
                    itm.item_quantity(ItemToPurchase._quantity)

        if count == 0:
            print(" ")
            print("Item not found in cart. Nothing modified.")

    def get_num_items_in_cart(self):
        count = 0
        itms = self.cart_items[:]
        for i in range(len(itms)):
            itm = itms[i]
            count += itm._quantity

        return count

    def get_cost_of_cart(self):
        cost = 0
        itms = self.cart_items[:]
        for i in range(len(itms)):
            itm = itms[i]
            cost += (itm._quantity * itm._price)

        return cost

    def print_total(self):
        print(self._customer_name + "'s Shopping Cart - " + self._current_date)
        count = len(self.cart_items)
        if count == 0:
            print(" ")
            print("SHOPPING CART IS EMPTY")
            return 0

        print("Number of Items: " + str(count))
        print(" ")     

        for itm in self.cart_items:
            itm.print_item_cost()

        total = self.get_cost_of_cart()
        print("Total: $" + str(total)) 

    def print_descriptions(self):
        print(self._customer_name + "'s Shopping Cart - " + self._current_date)
        print(" ")
        print("Item Descriptions")

        for itm in self.cart_itmes:
            print(itm.item_name() + ": " + itm.item_description()) 

def print_menu(cart):      
    print(" ")
    print("MENU")
    print("a - Add item to cart")
    print("r - Remove item from cart")
    print("c - Change item quntity")
    print("i - Output items' descriptions")
    print("o - Output shopping cart")
    print("q - Quit")
    print(" ") 

def main():
    #Define Constants and variables
    custName = ""
    dateToday = ""

    custName = input("Enter customer's name: ")
    dateToday = input("Enter today's date: ")

    print("Customer name: " + custName)
    print("Today's date: " + dateToday)

    myCart = ShoppingCart(custName,dateToday)

    option = ""

    while option != "q":
        print_menu(myCart)
        option = input("Choose an option: ").lower().strip()
        if option == "o":
            myCart.print_descriptions()
        elif option == "a":
            print("ADD ITEM TO CART")
            itemName = input("Enter the item name: ")
            itemDescr = input("Enter the item description: ")
            itemPrice = int(input("Enter the item price: "))
            itemQuantity = int(input("Enter the item quantity: "))
            print(" ")
            cartItem = ItemToPurchase()
            cartItem.item_name(itemName)
            cartItem.item_description(itemDescr)
            cartItem.item_price(itemPrice)
            cartItem.item_quantity(itemQuantity)
            myCart.add_item(cartItem)
        elif option == "r":
            print("REMOVE ITEM FROM CART")
            itemName = input("Enter name of item to remove: ")
            myCart.remove_item(itemName)
        elif option == "c":
            print("CHANGE ITEM QUNATITY")
            itemName = input("Enter the item name: ")
            itemQuantity = int(input("Enter the new quantity: "))
            changeItem = ItemToPurchase(itemName)
            changeItem.item_quantity(itemQuantity)
            myCart.modify_item(changeItem)

main()

I am getting the following error:

Enter customer's name: Rog
Enter today's date: Oct 20
Customer name: Rog
Today's date: Oct 20



MENU
a - Add item to cart
r - Remove item from cart
c - Change item quntity
i - Output items' descriptions
o - Output shopping cart
q - Quit



Choose an option: a
ADD ITEM TO CART
Enter the item name: Sketchers
Enter the item description: Black
Enter the item price: 120
Enter the item quantity: 2

Traceback (most recent call last): File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py", line 176, in main() File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py", line 163, in main myCart.add_item(cartItem) File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py", line 44, in add_item self.cart_items.append(cartItem) AttributeError: 'ShoppingCart' object has no attribute 'cart_items'

Can anyone tell me what I am doing incorrectly?




class ShoppingCart:

    def __init__(self, name="none", date="January 1, 2016"):
        cart_items = []
        _customer_name = name
        _current_date = date

These are all local variable. If you want them to be attributes of the instance, you have to explicitly refer to self:

class ShoppingCart:

    def __init__(self, name="none", date="January 1, 2016"):
        self.cart_items = []
        self._customer_name = name
        self._current_date = date



    This should give 29/29 points (Python)
    
       
    
     class ItemToPurchase:

  def __init__(self,
               item_name="none",
               item_price=0,
               item_quantity=0,
               item_description="none"):
    self.item_name = item_name
    self.item_price = item_price
    self.item_quantity = item_quantity
    self.item_description = item_description

  # prints out the item cost
  def print_item_cost(self):
    self.item_price = int(self.item_price)
    self.item_quantity = int(self.item_quantity)
    return f'{self.item_name} {self.item_quantity} @ ${self.item_price} = ${self.item_price*self.item_quantity}'

  # prints item_description attribute  for an itemToPurchase object
  def print_item_description(self):
    return f'{self.item_name}: {self.item_description}'


class ShoppingCart(ItemToPurchase):

  def __init__(self, customer_name, current_date):
    ItemToPurchase.__init__(self)
    self.customer_name = customer_name
    self.current_date = current_date
    self.cart_items = []

  # adds an item to cart_items
  def add_item(self, obj):
    self.cart_items.append(obj)

  # remove items from the cart
  def remove_item(self, item):
    count = 0
    for i in range(len(self.cart_items) - 1):
      if self.cart_items[i].item_name == item:
        self.cart_items.pop(i)
        count += 1
        break
    if count == 0:
      print("Item not found in cart. Nothing removed.")

  # modify item in cart by the name
  def modify_item(self, obj):
    for cart_item in self.cart_items:
      if cart_item.item_name == obj.item_name:
        cart_item.item_quantity = obj.item_quantity
    else:
      print("Item not found in cart. Nothing modified.")

  # returns the number of item in the list
  def get_num_items_in_cart(self):
    total_quantity = 0
    for x in self.cart_items:
      self.item_quantity = int(x.item_quantity)
      total_quantity += self.item_quantity
    return total_quantity

  # returns the total cost of items
  def get_cost_of_cart(self):
    cart_cost = 0
    for i in self.cart_items:
      self.item_price = int(i.item_price)
      self.item_quantity = int(i.item_quantity)
      cost = self.item_price * self.item_quantity
      cart_cost += cost
    return cart_cost

  # outputs total objects in cart
  def print_total(self):
    if len(self.cart_items) == 0:
      print(f'{self.customer_name}\'s Shopping Cart - {self.current_date}')
      print(f'Number of Items: {self.get_num_items_in_cart()}\n')
      print("SHOPPING CART IS EMPTY\n")
      print(f'Total: ${self.get_cost_of_cart()}')
    else:
      print(f'{self.customer_name}\'s Shopping Cart - {self.current_date}')
      print(f'Number of Items: {self.get_num_items_in_cart()}\n')
      for item in self.cart_items:
        print(item.print_item_cost())
      print()
      print(f'Total: ${self.get_cost_of_cart()}')

  # outputs the name of the item and description
  def print_descriptions(self):
    print(f'{self.customer_name}\'s Shopping Cart - {self.current_date}')
    print()
    print("Item Descriptions")
    for item in self.cart_items:
      print(item.print_item_description())

# menu
def print_menu():
    print("MENU")
    print("a - Add item to cart")
    print("r - Remove item from cart")
    print("c - Change item quantity")
    print("i - Output items' descriptions")
    print("o - Output shopping cart")
    print("q - Quit")
    
  


# excute menu
def execute_menu(char, cart):
  if char == "a":
    print("ADD ITEM TO CART")
    item_name = input("Enter the item name:\n")
    item_desc = input("Enter the item description:\n")
    item_price = input("Enter the item price:\n")
    item_quantity = input("Enter the item quantity:\n")
    item = ItemToPurchase(item_name, item_price, item_quantity, item_desc)
    cart.add_item(item)
    
  elif char == "r":
    print("REMOVE ITEM FROM CART")
    rmv_item = input("Enter name of item to remove:\n")
    cart.remove_item(rmv_item)
    
  elif char == "c":
    print("CHANGE ITEM QUANTITY")
    item_name = input("Enter the item name:\n")
    new_qunatity = input("Enter the new quantity:\n")
    new_obj = ItemToPurchase(item_name, sc.item_price, new_qunatity,
                             sc.item_description)
    cart.modify_item(new_obj)
    
  elif char == "i":
    print("OUTPUT ITEMS' DESCRIPTIONS")
    cart.print_descriptions()
  elif char == "o":
    print("OUTPUT SHOPPING CART")
    cart.print_total()


if __name__ == "__main__":
  choice = ""
  options = ["a", "r", "c", "i", "o", "q"]
  # parameters for ShoppingCart
  custo_name = input("Enter customer's name:\n")
  today_date = input("Enter today's date:\n")
  print()
  sc = ShoppingCart(custo_name, today_date)
  print(f'Customer name: {sc.customer_name}')
  print(f"Today's date: {sc.current_date}\n")
  print_menu()
  print()
  # while loop that prints the menu until user enters q - quit
  while True:
    
    choice = input("Choose an option:\n")
    if choice == "q":
      break
    else:
      if choice in options:
        execute_menu(choice, sc)
        print()
        print_menu()
        print()
      else:
        choice = input("Choose an option:\n")

반응형