异常:
下面定义了一个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("蜡烛还有库存!")
注释详细,就不多解释了!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/147472.html