没有括号的“ raise exception()”和“ raise exception”之间有区别吗?

问题:没有括号的“ raise exception()”和“ raise exception”之间有区别吗?

定义无参数异常:

class MyException(Exception):
    pass

举起时,它们之间是否有任何区别:

raise MyException

raise MyException()

我找不到任何东西。它仅仅是一个重载的语法吗?

Defining a parameterless exception:

class MyException(Exception):
    pass

When raised, is there any difference between:

raise MyException

and

raise MyException()

I couldn’t find any; is it simply an overloaded syntax?


回答 0

简短的回答是,无论raise MyExceptionraise MyException()做同样的事情。第一种形式会自动实例化您的异常。

docs相关部分说:“ 抬高将第一个表达式评估为异常对象。它必须是BaseException的子类或实例。如果是类,则在需要时通过使用实例化该类来获取异常实例。没有参数。”

也就是说,即使语义相同,第一种形式在微观上也更快,而第二种形式则更灵活(因为如果需要,可以将其传递给参数)。

大多数人在Python中(即在标准库,流行的应用程序和许多书中)使用的通常样式是在raise MyException没有参数的情况下使用。人们仅在需要传递一些参数时才直接实例化异常。例如: raise KeyError(badkey)

The short answer is that both raise MyException and raise MyException() do the same thing. This first form auto instantiates your exception.

The relevant section from the docs says, “raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.”

That said, even though the semantics are the same, the first form is microscopically faster, and the second form is more flexible (because you can pass it arguments if needed).

The usual style that most people use in Python (i.e. in the standard library, in popular applications, and in many books) is to use raise MyException when there are no arguments. People only instantiate the exception directly when there some arguments need to be passed. For example: raise KeyError(badkey).


回答 1

去看看raise声明的文档。它正在创建的实例MyException

Go look at the docs for the raise statement. It’s creating an instance of MyException.


回答 2

是的,ValueError和之间有区别ValueError()

ValueError是一个类,而ValueError()创建一个类的实例。这就是原因type(ValueError) is typetype(ValueError()) is ValueError

的唯一目的raise是引发异常,

当我们使用时ValueError,将调用class,该class依次运行构造函数 ValueError()

当我们使用时ValueError(),该方法ValueError()被直接调用。

注意: raise ValueError # shorthand for 'raise ValueError()'

Yep, there is a difference between ValueError and ValueError()

ValueError is a class whereas ValueError() creates an instance of a class. This is the reason the type(ValueError) is type and type(ValueError()) is ValueError

The sole purpose of raise is to raise the exception,

when we use ValueError, class will be called which in turn runs the constructor ValueError()

when we use ValueError(), the method ValueError() is directly called.

Note: raise ValueError # shorthand for 'raise ValueError()'