首页 > 解决方案 > 如果将参数传递给类,如何抛出自定义异常

问题描述

我有一个带装饰师的咖啡课。是否可以检查 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())

标签: pythonoop

解决方案


编写一个不带参数的构造函数,如果你传递一个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

推荐阅读