Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để in Cấu trúc phân cấp lỗi / ngoại lệ trong Python?

Chúng tôi nhập mô-đun kiểm tra và đặc biệt sử dụng hàm getclasstree () để in phân cấp ngoại lệ / lỗi python.

Đoạn mã này sắp xếp và in danh sách các lớp ngoại lệ đã cho thành một hệ thống phân cấp danh sách lồng nhau. Chúng tôi đi qua đệ quy __subclasses __ () xuống bởi một cây kế thừa như được hiển thị trong đầu ra.

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)

Đầu ra

Khi chạy mã, chúng tôi nhận được kết quả 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