Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract base class is not enforcing function implementation

from abc import abstractmethod, ABCMeta

class AbstractBase(object):
  __metaclass__ = ABCMeta

  @abstractmethod
  def must_implement_this_method(self):
      raise NotImplementedError()

class ConcreteClass(AbstractBase):

   def extra_function(self):
       print('hello')

   # def must_implement_this_method(self):
     # print("Concrete implementation")


d = ConcreteClass()  # no error
d.extra_function()

I'm on Python 3.4. I want to define an abstract base class that defines somes functions that need to be implemented by it's subclassses. But Python doesn't raise a NotImplementedError when the subclass does not implement the function...

like image 298
Jim Clermonts Avatar asked Jul 03 '15 08:07

Jim Clermonts


1 Answers

The syntax for the declaration of metaclasses has changed in Python 3. Instead of the __metaclass__ field, Python 3 uses a keyword argument in the base-class list:

import abc

class AbstractBase(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def must_implement_this_method(self):
        raise NotImplementedError()

Calling d = ConcreteClass() will raise an exception now, because a metaclass derived from ABCMeta can not be instantiated unless all of its abstract methods and properties are overridden (For more information see @abc.abstractmethod):

TypeError: Can't instantiate abstract class ConcreteClass with abstract methods
must_implement_this_method

Hope this helps :)

like image 139
elegent Avatar answered Sep 20 '22 23:09

elegent