简体   繁体   English

python编程中的OOP

[英]OOP in python programming

Hello guys am kind of new to programming in python language and was hoping if I get assistance from you. 大家好,我是python语言编程的新手,希望我能从您那里得到帮助。 The question is this: 问题是这样的:

  1. Create a class called ShoppingCart. 创建一个名为ShoppingCart的类。

  2. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. 创建一个不带参数的构造函数,并将total属性设置为零,并初始化一个空的dict属性,名为items。

  3. Create a method add_item that requires item_name, quantity and price arguments. 创建需要item_name,数量和价格参数的add_item方法。 This method should add the cost of the added items to the current value of total. 此方法应将已添加项目的成本添加到总计的当前值中。 It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. 它还应在项字典中添加一个条目,以便键为item_name,值为项的数量。

  4. Create a method remove_item that requires similar arguments as add_item. 创建一个方法remove_item,该方法需要与add_item类似的参数。 It should remove items that have been added to the shopping cart and are not required. 它应该删除已添加到购物车中的商品,而不是必需的。 This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. 此方法应从当前总计中扣除已删除项目的成本,并相应地更新项目dict。

  5. If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed. 如果要删除的项目数量超过购物车中该项目的当前数量,则假定要删除该项目的所有条目。

  6. Create a method checkout that takes in cash_paid and returns the value of balance from the payment. 创建一个方法checkout,它接受cash_paid并从付款中返回余额的值。 If cash_paid is not enough to cover the total, return "Cash paid not enough". 如果cash_paid不足以支付总金额,则返回“ Cash paid not too”。

  7. Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. Make sure Shop inherits from ShoppingCart. 创建一个名为Shop的类,该类具有一个不带任何参数的构造函数,并初始化一个名为数量的属性,数量为100。确保Shop继承自ShoppingCart。

  8. In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one 在Shop类中,重写remove_item方法,以便在不带参数的情况下调用Shop的remove_item会使数量减少1

And here is my code 这是我的代码

class ShoppingCart(object):

    def __init__(self):
        self.total = 0
        self.items = dict()

    def add_item(self, item_name, quantity, price):
        if item_name != None and quantity >= 1:
            self.items.update({item_name: quantity})
        if quantity and price >= 1:
            self.total += (quantity * price)

    def remove_item(self, item_name, quantity, price):
        self.total -= (quantity * price)
        try:
            if quantity >= self.items[item_name]:
                self.items.pop(item_name, None)
            self.items[item_name] -= quantity
        except(KeyError, RuntimeError):
            pass

    def checkout(self, cash_paid):
        balance = 0
        if cash_paid < self.total:
            return "Cash paid not enough"
        balance = cash_paid - self.total
        return balance


class Shop(ShoppingCart):

    def __init__(self):
        self.quantity = 100

    def remove_item(self):
        self.quantity -= 1

And the unittest 和单元测试

import unittest;

class Test(unittest.TestCase):
    def setUp(self):
        self.cart = ShoppingCart()
        self.shop = Shop()

    def test_cart_property_initialization(self):
        self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct')
        self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary')

    def test_add_item(self):
        self.cart.add_item('Mango', 3, 10)
        self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items')
        self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item')

    def test_add_item_hidden(self):
        self.cart.add_item('Mango', 3, 10)
        self.cart.add_item('Orange', 16, 10)
        self.assertEqual(self.cart.total, 190, msg='Cart total not correct after adding items')
        self.assertEqual(self.cart.items['Orange'], 16, msg='Quantity of items not correct after adding item')

    def test_remove_item(self):
        self.cart.add_item('Mango', 3, 10)
        self.cart.remove_item('Mango', 2, 10)
        self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item')
        self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item')

    def test_remove_item_hidden(self):
        self.cart.add_item('Mango', 3, 10)
        self.cart.add_item('Orange', 16, 10)
        self.cart.remove_item('Mango', 2, 10)
        self.assertEqual(self.cart.total, 170, msg='Cart total not correct after removing item')
        self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item')
        self.cart.remove_item('Mango', 2, 10)
        self.assertEqual(self.cart.total, 160, msg='Cart total not correct after removing item')
        with self.assertRaises(KeyError):
            self.cart.items['Mango']

    def test_checkout_returns_correct_value(self):
        self.cart.add_item('Mango', 3, 10)
        self.cart.add_item('Orange', 16, 10)
        self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct')
        self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct')


    def test_shop_is_instance_of_shopping_cart(self):
        self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart')

    def test_shop_initializaton(self):
        self.assertEqual(self.shop.quantity, 100, msg='Shop quantity not initialized correctly')

    def test_shop_remove_item_method(self):
        for i in range(15):
            self.shop.remove_item()

        self.assertEqual(self.shop.quantity, 85)

Now after running the unitest am getting this error message: 现在,在运行unitest之后会收到以下错误消息:

"150 != 160 : Cart total not correct after removing item" “ 150!= 160:删除项目后购物车总数不正确”

Anyone willing to help please will appreciate any guidelines. 任何愿意帮助的人都将感谢任何指导。

Looks like in the remove_item class attribute, you update the total value of the cart prior to determining if you are removing more items then you have. 看起来就像在remove_item类属性中,您在确定是否要删除更多物品之前更新购物车的总价值。

If you modify it so you check the item quantity first and then subtract the total number available if less than the total number wanted to be removed... it should fix the problem 如果您对其进行修改,那么您首先要检查项目数量,然后如果要删除的总数少于要删除的总数,则减去可用总数...这应该可以解决问题

def remove_item(self, item_name, quantity, price):
    try:
        if quantity >= self.items[item_name]:

            self.total -= (self.items[item_name] * price)
            self.items.pop(item_name, None)
        else:
            self.items[item_name] -= quantity
            self.total -= (quantity * price)

Your test is wrong. 您的测试是错误的。 Here your code checks that the cart total is 170 cash: 您的代码在这里检查购物车总额为170现金:

self.assertEqual(self.cart.total, 170, msg='Cart total not correct after removing item')

Then it removes 2 items at 10 cash each: 然后,它以10现金分别删除2个项目:

self.cart.remove_item('Mango', 2, 10)

Then it checks to see if there is 160 cash remaining: 然后,检查是否剩余160现金:

self.assertEqual(self.cart.total, 160, msg='Cart total not correct after removing item')

but it hasn't, it has 150 cash, which is what anyone would expect ( 170 - 20 = 150 ). 但它没有,它有150现金,这是任何人所期望的( 170 - 20 = 150 )。

The problem is with your add_item method you are not updating the item so each time you add the same item it doesn't update it just resigns the item_name and quantity again and forgets about the previous values so this is what your add_item method should look like: 问题在于您的add_item方法没有更新项目,因此每次添加同一项目都不会更新时,它只会再次item_namequantity ,而忘记了以前的值,因此这就是add_item方法的外观:

def add_item(self, item_name, quantity, price):
    self.total += price*quantity
    self.items.update({item_name: quantity})

This should work fine 这应该工作正常

class ShoppingCart(object):

    def __init__(self):
        self.total = 0
        self.items = dict()

    def add_item(self, item_name, quantity, price):
        if item_name != None and quantity >= 1:
            self.items.update({item_name: quantity})
        if quantity and price >= 1:
            self.total += (quantity * price)

    def remove_item(self, item_name, quantity, price):
        try:
            if quantity >= self.items[item_name]:

                self.total -= (self.items[item_name] * price)
                self.items.pop(item_name, None)

            else:
              self.items[item_name] -= quantity
              self.total -= (quantity * price)
        except IOError:
            print
            "Error: can\'t find file or read data"

    def checkout(self, cash_paid):
        balance = 0
        if cash_paid < self.total:
            return "Cash paid not enough"
        balance = cash_paid - self.total
        return balance


class Shop(ShoppingCart):   
    def __init__(self):
        self.quantity = 100

    def remove_item(self):
        self.quantity -= 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM