4
from abc import ABC, abstractmethodclass Example(ABC):    def smile(self):        print("smile")

My understanding is thatExample becomes anAbstractClass when it inherits theABCclass. AnAbstractClass can't be instantiated butthe following code executes without errors

example = Example()
askedMay 12, 2021 at 6:50
Kun.tito's user avatar
4
  • Add the @abstractmethod decorator so that the class must be overridden before it is instantiated.CommentedMay 12, 2021 at 7:49
  • Are you sayingExample isn't anAbstractClass until it contains an@abstractmethoddecorator? what then does inheritingABC do?CommentedMay 12, 2021 at 18:07
  • It does become abstract, although the methods that are contained inside are concrete. You need to make the methods inside abstract for you to not be able to instantiate it.CommentedMay 14, 2021 at 8:02
  • I've tried what would happen when there are two methods - one abstract one not - instantiating still throws an errorCommentedJan 24, 2024 at 12:02

1 Answer1

2

Your class does become abstract, although the method/methods that are contained inside (which issmile) 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, abstractmethodclass 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
answeredMay 14, 2021 at 8:10
hypadr1v3's user avatar
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.