“raise exception()”之间有区别和“引发例外”没有括号? [英] Is there a difference between "raise exception()" and "raise exception" without parenthesis?

查看:231
本文介绍了“raise exception()”之间有区别和“引发例外”没有括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义无参数异常:

class myException(Exception):
    pass

提出时,是否有区别:

raise myException

raise myException()

尝试时,我可以找到没有 - 这只是一个重载的语法?

When trying, I could find none - Is it simply an overloaded syntax?

推荐答案

简短的答案是,$ code> raise MyException raise MyException()做同样的事情。这个第一个表单自动实例化你的例外。

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

相关部分说, raise 将第一个表达式评估为异常对象,它必须是子类或BaseException的实例,如果它是一个类,那么在需要的时候通过实例化没有参数的类就可以获得异常实例。

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).

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

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).

这篇关于“raise exception()”之间有区别和“引发例外”没有括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆