Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python dict.get()中引发异常_Python_Dictionary_Exception Handling - Fatal编程技术网

在python dict.get()中引发异常

在python dict.get()中引发异常,python,dictionary,exception-handling,Python,Dictionary,Exception Handling,事实上,我已经知道我想做的有点奇怪,但我认为它会很好地适合我的代码,所以我问: 有没有办法做到这一点: foo = { 'a':1, 'b':2, 'c':3 } bar = { 'd':4, 'f':5, 'g':6 } foo.get('h', bar.get('h')) 在dict.get()失败的情况下引发异常而不是None foo.get('h',bar.get('h',raise))将引发SyntaxError foo.get('h',bar.get('h',Exception)

事实上,我已经知道我想做的有点奇怪,但我认为它会很好地适合我的代码,所以我问:

有没有办法做到这一点:

foo = { 'a':1, 'b':2, 'c':3 }
bar = { 'd':4, 'f':5, 'g':6 }

foo.get('h', bar.get('h'))
在dict.get()失败的情况下引发异常而不是
None

foo.get('h',bar.get('h',raise))
将引发
SyntaxError

foo.get('h',bar.get('h',Exception))
将只返回
Exception

现在我只是在处理
如果不是foo.get('h',bar.get('h'):引发异常
,但是如果有一种方法可以在
dict.get()中直接引发,我将非常高兴

谢谢

您可以:

class MyException(Exception):
    pass


try:
    value = dict['h']
except KeyError:
    raise MyException('my message')

使用下标,这是默认行为:

d={}
d['unknown key'] --> Raises a KeyError
如果然后要抛出自定义异常,可以执行以下操作:

try:
    d['unknown key']
except KeyError:
    raise CustomException('Custom message')
并包括来自KeyError的stacktrace:

try:
    d['unknown key']
except KeyError as e:
    raise CustomException('Custom message') from e

您可以使用magic函数为dict自定义类:

class GetAndRaise:
    def __init__(self):
        self.dict = dict()
    def __getitem__(self, key):
        try:
            return self.dict[key]
        except ValueError:
            raise MyException
    def __setitem__(self, key, value):
        self.dict[key] = value
    def get(self, key):
        return self[key]

既然你已经有了一些好的答案,我将给你一个有学问的答案

class MyDict(dict):
    def get(self, key, default=None, error=None):
        res = super().get(key,default)
        if res is None:
            if error == 'raise':
                raise SyntaxError()
            elif error == 'Exception':
                return SyntaxError()
        return res
现在您可以执行以下操作:

foo = MyDict({ 'a':1, 'b':2, 'c':3 })
bar = MyDict({ 'd':4, 'f':5, 'g':6 })
foo.get('h', bar.get('h', error="Exception")) #  returns a syntaxerror object
foo.get('h', bar.get('h', error="raise"))  # raises a syntax error

super()
允许您访问超类的成员,这样您就可以拥有自己的
get
,同时仍然在内部使用父类
get
,您可以使用容器
链图,它将两个字典封装成一个:

from collections import ChainMap

foo = { 'a':1, 'b':2, 'c':3 }
bar = { 'd':4, 'f':5, 'g':6 }

ChainMap(foo, bar)['h']

您可以将dict子类化,并使
get
执行您不想使用的
get()
,因为它会为您捕获索引器。如果你真的想要索引器,只需使用
foo['h']
回答“只需使用括号”是正确的,但这里有一个原因解释:另外,我保证在以后的过程中,
.get()
函数将对你有用。你也应该学习如何使用它。确切地说,我知道为什么要使用.get(),我只是想在找不到键时引发一个异常,而不是
None
,而不必使用条件。我不能容忍这种情况……请不要这样做,因为他正在寻找的功能已经在dict类中。“我会给你一个愚蠢的答案”看起来你有一些竞争。@TrebuchetMS当我开始写这篇文章时,没有那么多疯狂的回答。我已经知道了,我想用。get()因此,我不必使用条件句,但最后,看起来我无论如何都必须抱歉,也许是一个愚蠢的问题-这如何引发所需的异常,而不仅仅是从其他地方检索值?@VincentBuscarello如果值
h
不在链式dict中,您将得到
keyrerror
异常。