4

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?

M.javid
  • 6,387
  • 3
  • 41
  • 56
codingsplash
  • 4,785
  • 12
  • 51
  • 90

1 Answers1

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
nbro
  • 15,395
  • 32
  • 113
  • 196
M.javid
  • 6,387
  • 3
  • 41
  • 56