gpt4 book ai didi

python - 如何引发自定义字典 ​​KeyError 消息

转载 作者:太空狗 更新时间:2023-10-30 02:49:32 25 4
gpt4 key购买 nike

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

最佳答案

考虑这样做。

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

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

关于python - 如何引发自定义字典 ​​KeyError 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com