What should I put in the body of an abstract method in Python

Let's say I have the following abstract class Foo :

 import abc class Foo(abc.ABC): @abc.abstractmethod def bar(self): raise NotImplementedError 

What should I put in the body of the bar method?

I see a lot of code that has raise NotImplementedError as shown above. However, this seems redundant, since any subclass that does not implement bar will fine-tune TypeError: Can't instantiate abstract class Foo with abstract methods bar when it is created.

Can Pythonic leave bar empty as follows:

 import abc class Foo(abc.ABC): @abc.abstractmethod def bar(self): ... 

This is what is done in Python docs for Abstract base classes , but I'm not sure if this is just a placeholder or an actual example of how to write code.

If bar left with only three points ( ... ), when should I use NotImplementedError ?

+1
source share
1 answer

The documentation aims to give you an example. You do not have to follow it.

You can specify a default value; subclasses can still use super() to call your implementation. This is what most collections.abc classes do; see source code .

Size for example returns 0 for __len__ :

 class Sized(metaclass=ABCMeta): # ... @abstractmethod def __len__(self): return 0 
+5
source

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


All Articles