Equivalent of NotImplementedError for fields in Python

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

    An interesting pattern to handle this is to set attribute to None in the parent class and to access the attribute with a function that ensure it has been set in the child class.

    Here is an example from django-rest-framework:

    class GenericAPIView(views.APIView):
    
        [...]
    
        serializer_class = None
    
        [...]
    
        def get_serializer_class(self):
            assert self.serializer_class is not None, (
                "'%s' should either include a `serializer_class` attribute, "
                "or override the `get_serializer_class()` method."
                % self.__class__.__name__
            )
    
            return self.serializer_class
    

提交回复
热议问题