python - 如果将参数传递给类,如何抛出自定义异常
问题描述
我有一个带装饰师的咖啡课。是否可以检查 Americano 是否应该排在第一位?同时它必须是一次
class Americano(TO_ADD):
price = 60
class TO_ADD:
def calculate_cost(self):
return self.__class__.price
class Decorator(TO_ADD):
def __init__(self, addition):
self.components = addition
def calculate_cost(self):
return self.components.calculate_cost() + TO_ADD.calculate_cost(self)
class Cardamom(Decorator):
price = 7
def __init__(self, addition):
Decorator.__init__(self, addition)
class Syrop(Decorator):
price = 10
def __init__(self, addition):
Decorator.__init__(self, addition)
正确的例子
res = Cardamom(Syrop(Syrop(Syrop(Americano()))))
print(res.calculate_cost())
不正确的例子。在这种情况下,我需要抛出异常(自己)。怎么做?
res = Cardamom(Syrop(Syrop(Americano(Syrop()))))
print(res.calculate_cost())
解决方案
编写一个不带参数的构造函数,如果你传递一个TO_ADD
,它会抛出一个TypeError
class TO_ADD:
def __init__(self):
pass
或者,如果您需要自定义异常:
class TO_ADDException(Exception):
pass
class TO_ADD:
def __init__(self, *args, **kwargs):
if args or kwargs:
raise TO_ADDException("A TO_ADD is a basic element")
用一些更好的命名,并改进代码
class MaterialException(Exception):
pass
class Material:
price: int
def __init__(self, *args, **kwargs):
if args or kwargs:
raise MaterialException("A Material is a basic element and can't receive parameters")
def calculate_cost(self):
return self.price
class MaterialContainer(Material):
def __init__(self, mat: Material):
super().__init__()
self.mat = mat
def calculate_cost(self):
return self.price + self.mat.calculate_cost()
class Americano(Material):
price = 60
class Cardamom(MaterialContainer):
price = 7
class Syrop(MaterialContainer):
price = 10
采用
print(Cardamom(Syrop(Americano())).calculate_cost()) # 77
print(Cardamom(Syrop(Syrop(Syrop(Americano())))).calculate_cost()) # 97
print(Cardamom(Syrop(Syrop(Americano(Syrop(1))))).calculate_cost()) # TypeError
推荐阅读
- javascript - 使用 jQuery 创建元素
- visual-studio - Visual Studio 混淆
- reactjs - 如何使用 redux 工具包动态生成 reducer 和 action 类型?
- javascript - 如何使用javascript使用箭头键更改图像
- java - 如何使用按钮左右滑动图像视图
- java - Apache 配置无法加载文件属性 - 返回 null
- ajax - DotNetNuke 9 开发动态添加用户控件到编辑页面
- unity3d - Unity:通过编辑器脚本删除 LOD
- flutter - 如何将添加 SSL .cert 添加到 chopper 客户端?
- python - 我想自动化从 PDF 提取数据到 excel 的手动过程