python @abstractmethod decorator python @abstractmethod decorator python python

python @abstractmethod decorator


Are you using python3 to run that code? If yes, you should know that declaring metaclass in python3 have changes you should do it like this instead:

import abcclass AbstractClass(metaclass=abc.ABCMeta):  @abc.abstractmethod  def abstractMethod(self):      return

The full code and the explanation behind the answer is:

import abcclass AbstractClass(metaclass=abc.ABCMeta):    @abc.abstractmethod    def abstractMethod(self):        returnclass ConcreteClass(AbstractClass):    def __init__(self):        self.me = "me"# Will get a TypeError without the following two lines:#   def abstractMethod(self):#       return 0c = ConcreteClass()c.abstractMethod()

If abstractMethod is not defined for ConcreteClass, the following exception will be raised when running the above code: TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod


Import ABC from abc and make your own abstract class a child of ABC can help make the code look cleaner.

from abc import ABC, abstractmethodclass AbstractClass(ABC):  @abstractmethod  def abstractMethod(self):    returnclass ConcreteClass(AbstractClass):  def __init__(self):    self.me = "me"# The following would raise the TypeError complaining abstracteMethod is not impliementedc = ConcreteClass()  

Tested with Python 3.6