abc – python @abstractmethod decorator

abc – 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 abc

class AbstractClass(metaclass=abc.ABCMeta):

  @abc.abstractmethod
  def abstractMethod(self):
      return

The full code and the explanation behind the answer is:

import abc

class AbstractClass(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def abstractMethod(self):
        return

class ConcreteClass(AbstractClass):

    def __init__(self):
        self.me = me

# Will get a TypeError without the following two lines:
#   def abstractMethod(self):
#       return 0

c = ConcreteClass()
c.abstractMethod()

If abstractMethod is not defined for ConcreteClass, the following exception will be raised when running the above code: TypeError: Cant 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, abstractmethod

class AbstractClass(ABC):

  @abstractmethod
  def abstractMethod(self):
    return

class ConcreteClass(AbstractClass):
  def __init__(self):
    self.me = me

# The following would raise a TypeError complaining 
# abstractMethod is not implemented
c = ConcreteClass()  

Tested with Python 3.6

abc – python @abstractmethod decorator

Leave a Reply

Your email address will not be published. Required fields are marked *