Python自定义一个异常类【注释详细】

  • Post author:
  • Post category:python




异常:

下面定义了一个CandleShop类:

class CandleShop:
    name = "Here's a Hot Tip: Buy Drip Candles"

    def __init__(self, stock):
        self.stock = stock

    def buy(self, color):
        self.stock[color] = self.stock[color] - 1


candle_shop = CandleShop({'blue': 6, 'red': 2, 'green': 0})
candle_shop.buy('blue')

1)自定义一个异常类OutOfStack

2)请修改实例buy当购买蜡烛的量超出库存时会抛出OutOfStack异常

3)想办法在主程序中加一个代码会引起程序抛出OutOfStack

4)捕获该异常,并输出异常的具体信息。

class CandleShop:
    name = "Here's a Hot Tip: Buy Drip Candles"

    def __init__(self, stock):
        self.stock = stock

    def buy(self, color):
        self.stock[color] = self.stock[color] - 1


class OutOfStack(Exception):     # (1)自定义一个异常类OutOfStack
    pass


def new_buy(self, color):      # (2)动态修改实例buy当购买蜡烛的量超出库存时会抛出OutOfStack异常
        if self.stock[color] > 0:
            self.stock[color] = self.stock[color] - 1
        else:
            raise OutOfStack("购买蜡烛的量超出库存!")     # 产生异常


try:
    candle_shop = CandleShop({'blue': 6, 'red': 2, 'green': 0})
    CandleShop.buy = new_buy
    candle_shop.buy('blue')
    candle_shop.buy('green')      # (3)加一个代码会引起程序抛出OutOfStack
except OutOfStack as e:      # (4)捕获该异常
    print(e)  # 输出异常的具体信息
else:
    print("蜡烛还有库存!")

在这里插入图片描述

注释详细,就不多解释了!



版权声明:本文为qq_46556714原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。