5

I was trying out the below python code:

from abc import ABCMeta, abstractmethod class Bar: __metaclass__ = ABCMeta @abstractmethod def foo(self): pass class Bar2(Bar): def foo2(self): print("Foo2") b = Bar() b2 = Bar2() 

I thought having @abstractmethod will ensure that my parent class will be abstract and the child class would also be abstract as it is not implementing the abstract method. But here, I get no error trying to instantiate both the classes.

Can anyone explain why?

2
  • I did got exception b=Bar() TypeError: Can't instantiate abstract class Bar with abstract methods foo Commented Feb 24, 2015 at 5:50
  • @TanveerAlam Even I am surprised...I dont get the error...is it because of version? I am using 3.4 Commented Feb 24, 2015 at 5:52

1 Answer 1

7

You must set meta-class of Bar class to ABCMeta.

Python 2:

class Bar: __metaclass__ = ABCMeta @abstractmethod def foo(self): pass 

Python 3:

class Bar(object, metaclass=ABCMeta): @abstractmethod def foo(self): pass 
Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, there must be at least one abstract method in order for the error to be raised, like in your examples.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.