The body of an abstract method in Python 3.5

I have an abstract Model class, with several abstract methods, what should I put in the body of the methods?

  • Return

     class Model(metaclass=ABCMeta): @abstractmethod def foo(self): return 
  • Pass

     class Model(metaclass=ABCMeta): @abstractmethod def foo(self): pass 
  • Descriptive error increase

     class Model(metaclass=ABCMeta): @abstractmethod def foo(self): raise NotImplementedError("Class {class_name} doesn't implement {func_name} function" .format(class_name=self.__class__.__name__, func_name=self.__init__.__name__)) 

Normally, I would implement method 3 and raise an error, but it looks like it would be redundant, since Python is causing me an error:

 >>> bar = module.Model() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class Model with abstract methods foo 

Between the options presented, what is the best practice? Or is there another way I have to deal with this?

+5
source share
1 answer

The best thing to put in the body of an abstractmethod (or abstractproperty ) is a docstring.

Then you do not need pass or return or ... because return None implicitly included - and docstring makes this construct "compile" without SyntaxError :

 from abc import abstractmethod, ABCMeta class Model(metaclass=ABCMeta): @abstractmethod def foo(self): """This method should implement how to foo the model.""" 

Then the docstring should explain what needs to be implemented here so that the subclasses know what this / is intended to be.

+8
source

Source: https://habr.com/ru/post/1271126/


All Articles