Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)
edited by

You can use the abstract method decorator to declare a method abstract, and to declare a class abstract using one of three ways, depending upon which version of Python you are using.

If you are a  Python 3.4+ user then you can use the following code:-

from abc import ABC, abstractmethod

class Abstract(ABC):

@abstractmethod

def foo(self):

pass

Python 3.0+ users can use the following way:-

from abc import ABCMeta, abstractmethod

class Abstract(metaclass=ABCMeta):

@abstractmethod

def foo(self):

pass

At last, the Python 2 user can use the following code:-

from abc import ABCMeta, abstractmethod

class Abstract:

__metaclass__ = ABCMeta

@abstractmethod

def foo(self):

pass

Whatever versions you are using 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.

To know more about this you can have a look at the following video tutorial:-

Browse Categories

...