我不明白下面这段代码。对我来说,这看起来像是一种奇怪的语法。
super(CustomError, self).__init__(message, base_message, args)
class CustomError(Exception):
"""
Abstract Base class for all exceptions raised in this ecosystem.
"""
def __init__(self, message, base_message, *args):
"""
:param message:
Message to be displayed to user.
:param base_message:
Message to be passed to base class.
:param args:
Arguments to be passed to CustomError object.
"""
super(CustomError, self).__init__(message, base_message, args)
有人可以帮我了解这是内部做什么吗? base_message
和args
的目的是什么。
答案 0 :(得分:1)
CustomError类(子类)从Exception类(父类)继承。您引用的行调用了Parent类的构造函数。正如在CustomError的构造函数中调用的那样,这意味着在创建CustomeError的实例时,还会调用Parent类的构造函数。
消息是该异常的不同参数。
自定义错误似乎是将任何其他参数捆绑到一个tupple中。
请参见以下示例:
class CustomError(Exception):
"""
Abstract Base class for all exceptions raised in this ecosystem.
"""
def __init__(self, message, base_message, *args):
"""
:param message:
Message to be displayed to user.
:param base_message:
Message to be passed to base class.
:param args:
Arguments to be passed to CustomError object.
"""
super(CustomError, self).__init__(message, base_message, args)
try:
raise Exception('m1','m2',1,2,3)
except Exception as e:
print (e.args) #('m1', 'm2', 1, 2, 3)
try:
raise CustomError('m1','m2',1,2,3)
except CustomError as c:
print (c.args) #('m1', 'm2', ([1, 2, 3],))