0

I have been reading up on the distinction between virtual vs abstract methods. This is well documented. Difference between virtual and abstract methods

Virtual methods have an implementation and provide the derived classes with the option of overriding it.

Abstract methods do not provide an implementation and force the derived classes to override the method.

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method.

Based on these statements, it sounds like methods decorated with abc.abstractmethod should have no implementation, only either pass, ... (used in abc docs), or raise NotImplementedError.


It seems programmers commonly use abc.abstractmethod to implement a virtual function, where overriding is mandatory. This can be seen in many places:

However, this seems to go against the very definition of the design pattern for abstract methods having no body.

This answer makes a good point on the subject matter.


My observation is the virtual vs abstract method design pattern is currently loosely followed in Python.

Can anyone shed light on this? What is the best practice?

Community
  • 1
  • 1
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
  • 1
    to put it simply, Python != C# Note, in the C++ sense, *all python methods are virtual*. Not all terminologies perfectly align or are relevant across languages. – juanpa.arrivillaga May 02 '20 at 20:01
  • 2
    Note, virtual methods as a distinct thing don't make sense in Python, because *all* methods are overridable/inheritable, because the runtime type of an object *always* determines what method is called, there are no static/compile-time types in Python to allow for non-virtual methods to begin with, so that isn't really a useful distinction or category. – juanpa.arrivillaga May 02 '20 at 20:08
  • Even an abstract method has to have some body (we all need somebody). Generally, I would just use `pass` as the method body for an abstract method. There is no point in using `raise NotImplementedError.` because a class that inherits from an abstract base class that does not override the abstract method will throw an exception once you try to instantiate an object of that class, so you will never have a chance to attempt to call the abstract method. – Booboo May 02 '20 at 20:15

0 Answers0