Cải thiện trên @mkorpela câu trả lời tuyệt vời , đây là một phiên bản với
kiểm tra chính xác hơn, đặt tên và nâng cao các đối tượng Lỗi
def overrides(interface_class):
"""
Function override annotation.
Corollary to @abc.abstractmethod where the override is not of an
abstractmethod.
Modified from answer https://stackoverflow.com/a/8313042/471376
"""
def confirm_override(method):
if method.__name__ not in dir(interface_class):
raise NotImplementedError('function "%s" is an @override but that'
' function is not implemented in base'
' class %s'
% (method.__name__,
interface_class)
)
def func():
pass
attr = getattr(interface_class, method.__name__)
if type(attr) is not type(func):
raise NotImplementedError('function "%s" is an @override'
' but that is implemented as type %s'
' in base class %s, expected implemented'
' type %s'
% (method.__name__,
type(attr),
interface_class,
type(func))
)
return method
return confirm_override
Đây là những gì nó trông giống như trong thực tế:
NotImplementedError" không được thực hiện trong lớp cơ sở "
class A(object):
# ERROR: `a` is not a implemented!
pass
class B(A):
@overrides(A)
def a(self):
pass
dẫn đến NotImplementedErrorlỗi mô tả nhiều hơn
function "a" is an @override but that function is not implemented in base class <class '__main__.A'>
đầy đủ ngăn xếp
Traceback (most recent call last):
…
File "C:/Users/user1/project.py", line 135, in <module>
class B(A):
File "C:/Users/user1/project.py", line 136, in B
@overrides(A)
File "C:/Users/user1/project.py", line 110, in confirm_override
interface_class)
NotImplementedError: function "a" is an @override but that function is not implemented in base class <class '__main__.A'>
NotImplementedError" loại thực hiện dự kiến "
class A(object):
# ERROR: `a` is not a function!
a = ''
class B(A):
@overrides(A)
def a(self):
pass
dẫn đến NotImplementedErrorlỗi mô tả nhiều hơn
function "a" is an @override but that is implemented as type <class 'str'> in base class <class '__main__.A'>, expected implemented type <class 'function'>
đầy đủ ngăn xếp
Traceback (most recent call last):
…
File "C:/Users/user1/project.py", line 135, in <module>
class B(A):
File "C:/Users/user1/project.py", line 136, in B
@overrides(A)
File "C:/Users/user1/project.py", line 125, in confirm_override
type(func))
NotImplementedError: function "a" is an @override but that is implemented as type <class 'str'> in base class <class '__main__.A'>, expected implemented type <class 'function'>
Điều tuyệt vời về câu trả lời @mkorpela là kiểm tra xảy ra trong một số giai đoạn khởi tạo. Kiểm tra không cần phải được "chạy". Đề cập đến các ví dụ trước, class Bkhông bao giờ được khởi tạo ( B()) nhưng vẫn NotImplementedErrorsẽ tăng. Điều này có nghĩa là overrideslỗi được bắt sớm hơn.