How to Fix Python Error ‘Can’t Instantiate Abstract Class’

Here’s the fix for can’t instantiate abstract class error. Also explained the reason for it. A class that derives from the ABC class belonging to the ABC module is called an abstract class. ABC class a.k.a metaclass. Precisely, it is a class that defines the behavior of other classes. So a class that defines from ABC is called metatclass.

Abstract Class

There are two conditions to becoming an abstract class. One is to pass ‘ABC’ to a class, and it should have an ‘abstract method.’ An abstract method is a template, and concrete is a definition.

Rules for Abstract class

  • The objects of an abstract class cannot be created by PVM (python virtual machine).
  • It is not mandatory to declare all the methods as abstract in an abstract class.
  • The class must be abstract if there is any abstract method in a class.
  • Defining the abstract methods of an abstract class must be in its child class/subclass.
  • If any abstract class is inherited which have an abstract method, then either implementation of the method or making this class abstract must be provided.
  • An abstract class can have an abstract method and a concrete method.
Advertisements

Abstract class that threw error

from abc import ABC,abstractmethod

class one(ABC):
    @abstractmethod
    def move(self):
        pass
obj_one=one()

When you run this code, it throws an error – “TypeError: Can’t instantiate abstract class one with abstract methods move

TypeError: Can't instantiate abstract class one with abstract methods move

The reasons for error

The reason is abstract-method not implemented in the child class. So we got the error. Here’s the revised code, which fixes the error.

Implementing the abstract method

The error ‘Can’t Instantiate Abstract Class’ is fixed and not displayed now.

Recommended books

Related posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.