Able to instantiate a python class even though it is abstract (using abc)

This relates to the answer to this question on "Use the python abc module to create abstract classes". (by @alexvassel and accepted as the answer).

I tried the sentences, but, oddly enough, even though I used the abc method, this does not work for me. So I post 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 run this module, here is the output on my console:

 pydev debugger: starting (pid: 20388) tst 

in contrast to the accepted answer

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

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

+6
source share
2 answers

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() 
+7
source

In Python 2, you should assign a metaclass as follows:

 import abc class ABC(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def foo(self): return True a = ABC() 

What causes a TypeError

 Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> a = ABC() TypeError: Can't instantiate abstract class ABC with abstract methods foo 

But in Python 3, assigning __metaclass__ as an attribute does not work (as you intend it, but the interpreter does not consider it an error, and the regular attribute is like any other, so the code above will not lead to an error). Metaclasses are now defined as a named argument to the class:

 import abc class ABC(metaclass=abc.ABCMeta): @abc.abstractmethod def foo(self): return True a = ABC() 

raises a TypeError :

 Traceback (most recent call last): File "main.py", line 11, in a = ABC() TypeError: Can't instantiate abstract class ABC with abstract methods foo 
+4
source

Source: https://habr.com/ru/post/970879/


All Articles