5

我正在编写一些非 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

4

1 回答 1

5

考虑这样做。

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

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

于 2011-10-17T18:31:53.197 回答