【问题标题】:How to raise custom dictionary KeyError message如何引发自定义字典 ​​KeyError 消息
【发布时间】:2011-12-09 12:30:51
【问题描述】:

我正在编写一些非 python 用户将使用的脚本。我有一个包含字典的 Config 类,我希望能够为 KeyError 引发自定义异常。除了编写一个在检查字典中的值时引发异常的方法之外,是否还有一种优雅的方法可以做到这一点?

这是一个例子:

class ConfigError(Exception): pass

class Config:
    def __init__(self):
        self.cars = {'BMW': 'M5', 'Honda': 'Civic'}

    def get_car(self, name):
        try:
            return self.cars[name]
        except KeyError, e:
            raise ConfigError("Car %s doesn't exist!!!" % name)

conf = Config()
print 'Car: %s' % conf.cars['BMW']
print 'Car: %s' % conf.cars['Mercedes']

这是输出:

Car: M5 
Traceback (most recent call last):
  File "test.py", line 17, in ?
    print 'Car: %s ' % conf.cars['Mercedes']
KeyError: 'Mercedes'

我知道我可以编写像上面的 Config.get_car() 这样的方法并引发自定义异常,但我希望能够在直接尝试访问 Config.cars 字典时引发自定义异常。我想这样做是因为配置中实际上有更多字典,但我只需要为其中一个字典引发自定义异常,并希望保持数据访问方式的一致性(全部作为字典)。

注意:这是使用 Python 2.4.4

【问题讨论】:

    标签: python exception-handling dictionary python-2.4


    【解决方案1】:

    考虑这样做。

    class MyConfigDict( dict ):
        def __getitem__( self, key ):
            try:
                return super( MyConfigDict, self ).__getitem__( key )
            except KeyError as e:
                raise MyConfigError( e.message )
    

    类似的东西可能允许您将每个访问都包装在您自己的扩展异常中。

    【讨论】:

    • 我能问一下为什么使用super().__getitem__(key)而不是self.__getitem__(key)吗?
    • 因为有问题的代码定义了self.__getitem__(key)。我们想要的行为是使用字典的默认行为(即super().__getitem__(key),如果失败则引发自定义错误。如果我们按照建议调用self.__getitem__(key),我们将进入递归循环
    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2019-11-13
    相关资源
    最近更新 更多