Chúng ta import module inspect và cụ thể dùng hàm getclasstree() để in Python Exception/Error hierarchy.
Code này arrange và print danh sách exception classes cho trước thành hierarchy của nested lists. Chúng ta đệ quy đi qua __subclasses__() xuống theo inheritance tree như trong output.
Ví dụ
import inspect
print("The class hierarchy for built-in exceptions is:")
inspect.getclasstree(inspect.getmro(BaseException))
def classtree(cls, indent=0):
print('.' * indent, cls.__name__)
for subcls in cls.__subclasses__():
classtree(subcls, indent + 3)
classtree(BaseException)
Kết quả
Khi chạy code chúng ta nhận được output sau:
The class hierarchy for built-in exceptions is: BaseException ... Exception ...... StandardError ......... TypeError ......... ImportError .......... ZipImportError ......... EnvironmentError .......... IOError .......... OSError ............. WindowsError ......... EOFError ......... RuntimeError .......... NotImplementedError ......... NameError .......... UnboundLocalError ......... AttributeError ......... SyntaxError .......... IndentationError ............. TabError ......... LookupError .......... IndexError .......... KeyError .......... CodecRegistryError ......... ValueError .......... UnicodeError ............. UnicodeEncodeError ............. UnicodeDecodeError ............. UnicodeTranslateError ......... AssertionError ......... ArithmeticError .......... FloatingPointError .......... OverflowError .......... ZeroDivisionError ......... SystemError .......... CodecRegistryError ......... ReferenceError ......... MemoryError ......... BufferError ...... StopIteration ...... Warning ......... UserWarning ......... DeprecationWarning ......... PendingDeprecationWarning ......... SyntaxWarning ......... RuntimeWarning ......... FutureWarning ......... ImportWarning ......... UnicodeWarning ......... BytesWarning ...... _OptionError ...... error ...... Error ...... TokenError ...... StopTokenizing ...... error ...... EndOfBlock ... GeneratorExit ... SystemExit ... KeyboardInterrupt