Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, Can an abstract class be instantiated?

from abc import ABC, abstractmethod

class Example(ABC):
    def smile(self):
        print("smile")

My understanding is that Example becomes an AbstractClass when it inherits the ABC class. An AbstractClass can't be instantiated but the following code executes without errors

example = Example()
like image 964
Kun.tito Avatar asked Sep 19 '25 10:09

Kun.tito


1 Answers

Your class does become abstract, although the method/methods that are contained inside (which is smile) is/are concrete. You need to make the methods inside abstract using the decorator @abc.abstractclass. Thus, if you rewrite your code to:

from abc import ABC, abstractmethod

class Example(ABC):
    @abstractmethod
    def smile(self):
        print("smile")
        
e = Example()

then you would get the error:

TypeError: Can't instantiate abstract class Example with abstract methods smile
like image 174
hypadr1v3 Avatar answered Sep 21 '25 00:09

hypadr1v3