问题
I have been searching online to understand the usage of Exception.__init__(self)
for user defined exceptions.
For example:
I have two user defined exceptions with one Exception.__init__(self)
and second without.
class MyFirstError(Exception):
def __init__(self, result):
Exception.__init__(self)
self.result = result
class MySecondError(Exception):
def __init__(self, result):
self.result = result
def test():
try:
raise MyFirstError("__My First Error__")
except MyFirstError as exc:
return exc.result
def test2():
try:
raise MySecondError("__ My Second Error__")
except MySecondError as exc:
return exc.result
if __name__ == "__main__":
print(test())
print(test2())
Output:
__My First Error__
__ My Second Error__
Both of them doing similar stuff. I couldn't understand the difference.
回答1:
More correct syntax would be super().__init__()
for Python3 or super(MyFirstError, self).__init__()
for Python2.
You typically do this when override __init__()
in a subclass and need base class constructor to be called as well. In your particular case there's no any benefit of calling base Exception constructor with no parameters as it's not doing anything fancy, but you may want to pass the result
to the Exception constructor so that you don't have to keep self.result
yourself in a subclass.
Example:
class MyFirstError(Exception):
def __init__(self, result):
super().__init__(result) # will pass result as an argument to the base Exception class
Though, same thing could be also done in much shorter way:
class MyFirstError(Exception): pass
As you don't implement the constructor, base Exception's __init__(result)
method will be implicitly called achieving exactly the same result as above.
来源:https://stackoverflow.com/questions/56900247/use-of-exception-init-self-for-user-defined-exceptions