from abc import ABC, abstractmethodclass Example(ABC): def smile(self): print("smile")
My understanding is thatExample
becomes anAbstractClass
when it inherits theABC
class
. AnAbstractClass
can't be instantiated butthe following code executes without errors
example = Example()
- Add the @abstractmethod decorator so that the class must be overridden before it is instantiated.hypadr1v3– hypadr1v32021-05-12 07:49:35 +00:00CommentedMay 12, 2021 at 7:49
- Are you saying
Example
isn't anAbstractClass
until it contains an@abstractmethod
decorator
? what then does inheritingABC
do?Kun.tito– Kun.tito2021-05-12 18:07:43 +00:00CommentedMay 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.hypadr1v3– hypadr1v32021-05-14 08:02:29 +00:00CommentedMay 14, 2021 at 8:02
- I've tried what would happen when there are two methods - one abstract one not - instantiating still throws an errorstam– stam2024-01-24 12:02:06 +00:00CommentedJan 24, 2024 at 12:02
1 Answer1
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
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.