Equivalent of NotImplementedError for fields in Python

前端 未结 8 1357
北海茫月
北海茫月 2020-12-07 18:56

In Python 2.x when you want to mark a method as abstract, you can define it like so:

class Base:
    def foo(self):
        raise NotImplementedError(\"Subcl         


        
8条回答
  •  心在旅途
    2020-12-07 19:46

    And here is my solution:

    def not_implemented_method(func):
        from functools import wraps
        from inspect import getargspec, formatargspec
    
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            c = self.__class__.__name__
            m = func.__name__
            a = formatargspec(*getargspec(func))
            raise NotImplementedError('\'%s\' object does not implement the method \'%s%s\'' % (c, m, a))
    
        return wrapper
    
    
    def not_implemented_property(func):
        from functools import wraps
        from inspect import getargspec, formatargspec
    
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            c = self.__class__.__name__
            m = func.__name__
            raise NotImplementedError('\'%s\' object does not implement the property \'%s\'' % (c, m))
    
        return property(wrapper, wrapper, wrapper)
    

    It can be used as

    class AbstractBase(object):
        @not_implemented_method
        def test(self):
            pass
    
        @not_implemented_property
        def value(self):
            pass
    
    class Implementation(AbstractBase):
        value = None
    
        def __init__(self):
            self.value = 42
    
        def test(self):
            return True
    

提交回复
热议问题