Search code examples
pythonpython-3.xabstract-classpython-2.xabstract-base-class

Able to instantiate python class, in spite of it being Abstract (using abc)


This is in reference to the answer for this question to "Use abc module of python to create abstract classes." (by @alexvassel and accepted as an answer).

I tried the suggestions, but strangely enough, in spite of following the suggestions to use the abc way, it doesn't work for me. Hence I am posting it as a question here:

Here is my Python code:

from abc import ABCMeta, abstractmethod

class Abstract(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        print("tst")

a = Abstract()
a.foo()

When I execute this module, here is the output on my console:

pydev debugger: starting (pid: 20388)
tst

as opposed to that accepted answer

>>> TypeError: Can not instantiate abstract class Abstract with abstract methods foo

So what am I doing right or wrong? Why does work and not fail? Appreciate any expert insight into this.


Solution

  • In Python 3 use the metaclass argument when creating the abstract base class:

    from abc import ABCMeta, abstractmethod
    
    class Abstract(metaclass=ABCMeta):
    
        @abstractmethod
        def foo(self):
            print("tst")
    
    a = Abstract()
    a.foo()