How can I make a class or method abstract in Python?
I tried redefining __new__() like so:
class F:
def __new__(cls):
raise Exception("Unable to create an instance of abstract class %s" %cls)
But now, if I create a class G that inherits from F like so:
class G(F):
pass
Then, I can’t instantiate G either, since it calls its super class’s __new__ method.
Is there a better way to define an abstract class?
Use the
abcmodule to create abstract classes. Use theabstractmethoddecorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.In Python 3.4 and above, you can inherit from
ABC. In earlier versions of Python, you need to specify your class’s metaclass asABCMeta. Specifying the metaclass has different syntax in Python 3 and Python 2. The three possibilities are shown below:Whichever way you use, you won’t be able to instantiate an abstract class that has abstract methods, but will be able to instantiate a subclass that provides concrete definitions of those methods: