Home > Back-end >  How come an abstract base class in python can be instantiated?
How come an abstract base class in python can be instantiated?

Time:02-03

It is very surprising to me that I can instantiate an abstract class in python:

from abc import ABC

class Duck(ABC):
    def __init__(self, name):
        self.name = name

if __name__=="__main__":
    d = Duck("Bob")
    print(d.name)

The above code compiles just fine and prints out the expected result. Doesn't this sort of defeat the purpose of having an ABC?

CodePudding user response:

If you have no abstract method, you will able to instantiate the class. if you have at least one, you will not. In code that would read like

from abc import ABC, abstractmethod

class Duck(ABC):
    def __init__(self, name):
        self.name = name

    @abstractmethod
    def implement_me(self):
        ...

if __name__=="__main__":
    d = Duck("Bob")
    print(d.name)

TypeError: Can't instantiate abstract class Duck with abstract method implent_me

It is the combination of the ABC metaclass, and at least one abstractmethod that will lead to you not being able to instantiate a class. If you leave out one of the two, you will be able to do so.

  •  Tags:  
  • Related