Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch NotImplementedError Exception trong Python?

User-defined base classes có thể raise NotImplementedError để chỉ ra rằng một method hoặc behavior cần được định nghĩa bởi subclass, mô phỏng interface. Exception này derived từ RuntimeError. Trong user defined base classes, abstract methods nên raise exception này khi chúng yêu cầu derived classes override method.

Ví dụ

import sys
try:
    class Super(object):
        @property
        def example(self):
            raise NotImplementedError("Subclasses should implement this!")
    s = Super()
    print(s.example)
except Exception as e:
    print(e)
    print(sys.exc_type)

Kết quả

Subclasses should implement this!
<type 'exceptions.NotImplementedError'>