在Python中创建一个类的列表作为第二个类的属性

时间:2018-10-21 00:30:04

标签: python list class

我在Python中有一个介绍性类,其中的部分说明是:

(2)使用以下数据属性和相关方法构建ShoppingCart类。注意:最初可能是一些方法存根(空方法),将在以后的步骤中完成。

  • 以客户名称和日期为参数的参数化构造函数
  • 属性
  • customer_name(字符串)-在默认构造函数中初始化为“ none”
  • current_date(字符串)-在默认构造函数中初始化为“ 2016年1月1日”
  • cart_items(列表)
  • 方法
  • add_item()

  • 将项目添加到cart_items列表。具有参数ItemToPurchase。不返回任何内容。

代码是:

    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()

我遇到以下错误:

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
  

回溯(最近通话最近):文件   “ C:\ PythonWorkspace \ Chapter9Assignment \ src \ onlineShoppingCart2.py”,   176行,在       main()文件“ C:\ PythonWorkspace \ Chapter9Assignment \ src \ onlineShoppingCart2.py”,   主线163       myCart.add_item(cartItem)文件“ C:\ PythonWorkspace \ Chapter9Assignment \ src \ onlineShoppingCart2.py”,   add_item中的第44行       self.cart_items.append(cartItem)AttributeError:“ ShoppingCart”对象没有属性“ cart_items”

谁能告诉我我做错了什么?

1 个答案:

答案 0 :(得分:1)

class ShoppingCart:

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

这些都是局部变量。如果希望它们成为实例的属性,则必须显式引用self

class ShoppingCart:

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