7

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?

3
  • 2
    If you have no abstract methods, what's the point of using an ABC? Commented Feb 2, 2022 at 7:44
  • Good point, but then it would be nice if the docs explicitly stated that the combination of ABC and abstractmethod is what makes a true abstract class in python. Commented Feb 2, 2022 at 7:48
  • 2
    It's explicitly stated in the PEP (search for "at least one method"). And it's sort-of stated in the docs too ("...cannot be instantiated unless all of its abstract methods and properties are overridden" - if there are no abstract methods, then it's actually true that all of them have been overridden) Commented Feb 2, 2022 at 9:18

2 Answers 2

10

If you have no abstract method, you will able to instantiate the class. If you have at least one, you will not.

Consider the following code:

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) 

which returns:

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Not true. I was able to compile your code no problem.
@user32882 no, this answer is correct. The above code compiles just fine, but throws that runtime error.
Never mind. You're right, adding an abstractmethod means the code won't run...
0

I had the same problem! I guess we can just make __init__() abstract:

from abc import ABC, abstractmethod class Duck(ABC): @abstractmethod def __init__(self, name): self.name = name 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.