比兹利,大卫。 Python 食谱(第 578 页)。奥莱利媒体。
如果你要定义一个新的异常覆盖
Exception 的 init() 方法,请确保始终使用所有传递的参数调用 Exception.init()。例如:
:
class CustomError(Exception):
def __init__(self, message, status):
super().__init__(message, status)
self.message = message
self.status = status
这可能看起来有点奇怪,但 Exception 的默认行为
是接受所有传递的参数并将它们存储在 .args
属性作为元组。 Python 的各种其他库和部分
期望所有异常都有 .args 属性,所以如果你跳过这个
步骤,你可能会发现你的新异常表现得不太好
在某些情况下是正确的。为了说明 .args 的使用,请考虑
这个带有内置 RuntimeError 异常的交互式会话,以及
注意 raise 可以使用任意数量的参数
声明:
菲利普斯,达斯蒂。 Python 3 面向对象编程:使用 Python 3.8 第 3 版中的面向对象设计模式构建健壮且可维护的软件(第 119 页)
class AuthException(Exception):
def __init__(self, username, user=None):
super().__init__(username, user)
self.username = username
self.user = user
class UsernameAlreadyExists(AuthException):
pass
class PasswordTooShort(AuthExceptio)
pass
我必须注意,与其通过,不如按照 Luciano Ramalho 的建议在此处添加字符串文档
让我们看看它的用途
class Authenticator:
def __init__(self):
"""Construct an authenticator to manage
users logging in and out."""
self.users = {}
def add_user(self, username, password):
if username in self.users:
raise UsernameAlreadyExists(username)
if len(password) < 6:
raise PasswordTooShort(username)
self.users[username] = User(username, password)
希望对你有帮助