查找实例变量中的最低值

时间:2014-11-23 22:44:10

标签: python-3.x

class ShoppingCart:

    def __init__(self):
        self.cart = []

    def add_item(self, item):
        """ (ShoppingCart, Item) -> NoneType
        Adds an item to the cart.
        """
        self.cart.append(item)

    def show_cheapest_item(self):
        """ (ShoppingCart) -> int
        Return the cheapest item in the cart, or -1 if no items are in the cart
        """
        # my point of confusion

class Item:

    """ An instance of an item """
    def __init__(self, price):
        """ (Item, float)
        Initialize an Item
        """
        self.price = price

我正在尝试退回购物车中最便宜的商品,但是,我无法以任何方式访问价目表。

3 个答案:

答案 0 :(得分:0)

def show_cheapest_item(self):
    """ (ShoppingCart) -> int
    Return the cheapest item in the cart, or -1 if no items are in the cart
    """
    if len(self.cart) == 0:
        return -1
    cheapest_item = self.cart[0]
    for item in self.cart[1:]:
        if item.price < cheapest_item.price:
            cheapest_item = item
    return cheapest_item

答案 1 :(得分:0)

class ShoppingCart:

    def __init__(self):
        self.cart = []

    def add_item(self, item):
       """ (ShoppingCart, Item) -> NoneType
       Adds an item to the cart.
       """
       self.cart.append(item)

    def show_cheapest_item(self):
       """ (ShoppingCart) -> int
       Return the cheapest item in the cart, or -1 if no items are in the cart
       """
       return -1 if len(self.cart) == 0 else min(self.cart)

答案 2 :(得分:0)

使用minoperator.attrgetter

import operator

def show_cheapest_item(self):
    """ (ShoppingCart) -> int
    Return the cheapest item in the cart, or -1 if no items are in the cart
    """
    return -1 if not self.cart else min(self.cart, key=operator.attrgetter('price'))