from abc import abstractmethod, ABCMetaclass AbstractBase(object):__metaclass__ = ABCMeta@abstractmethoddef 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...
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 abcclass AbstractBase(metaclass=abc.ABCMeta):@abc.abstractmethoddef 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 :)