Equivalent of NotImplementedError for fields in Python

前端 未结 8 1362
北海茫月
北海茫月 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:48

    Here is a simple example how to set required properties/methods for sublasses in Python 3.

    class Base:
        requires = ('foo', 'bar')
    
        def __init_subclass__(cls, **kwargs):
            for requirement in cls.requires:
                if not hasattr(cls, requirement):
                    raise NotImplementedError(
                            f'"{cls.__name__}" must have "{requirement}".')
            super().__init_subclass__(**kwargs)
    

提交回复
热议问题