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

问题描述 投票:0回答:3

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

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

  • 参数化构造函数,以客户名称和日期作为参数
  • 属性
  • customer_name(字符串)- 在默认构造函数中初始化为“none”
  • current_date(字符串)- 在默认构造函数中初始化为“2016 年 1 月 1 日”
  • 购物车项目(列表)
  • 方法
  • 添加_项目()

  • 将商品添加到 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”, 第 44 行,在 add_item 中 self.cart_items.append(cartItem) AttributeError: 'ShoppingCart' 对象没有属性 'cart_items'

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

python list class
3个回答
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

1
投票
    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")

0
投票

我一直在研究这个实验室的第一部分,我想分享它,以防人们发现它有帮助:P 我知道我对一些价值观的命名很糟糕,但是嘿,你能做什么,我觉得这很有趣

class ItemToPurchase:
def __init__(self, name = "none", price = 0, quantity= 0, description= "none"):
    self.item_name = name
    self.item_price = price
    self.item_quantity = quantity
    self.item_description = description
def __str__(self):
    print(f"For item {self.item_name}: {self.item_description} there are {self.item_quantity} available at $ {self.item_price}.")

def print_item_cost(self):
    print(f'{self.item_name} {self.item_quantity} @ ${self.item_price} = ${self.item_price * self.item_quantity}')

def print_item_description(self):
    print(f'{self.item_name}: {self.item_description}')  

您可以看到我的 ItemToPurchase init 方法与第一篇文章有何不同,但与 14 :3 相比,我在 5 行中定义了所有术语(我知道我在吹牛,而我的打印部分看起来像一个粗略的战争草图和平,但是这门课是我第一次编码,所以让我休息一下吧)

if name == "main":

test= ItemToPurchase()
print('Item 1')
test.item_name = input("Enter the item name:")
print()
test.item_price= int(input("Enter the item price:"))
print()
test.item_quantity = int(input("Enter the item quantity:"))
print()

lame= ItemToPurchase()
print()
print('Item 2')
lame.item_name = input("Enter the item name:")
print()
lame.item_price= int(input("Enter the item price:"))
print()
lame.item_quantity = int(input("Enter the item quantity:"))
print()
print()

print('TOTAL COST')
test.print_item_cost()
lame.print_item_cost()
print()
print(f'Total: ${lame.item_price * lame.item_quantity + test.item_price * test.item_quantity}')
© www.soinside.com 2019 - 2024. All rights reserved.