Verwenden Sie abc.ABCMeta so, dass es sowohl mit Python 2.7 als auch mit Python 3.5 kompatibel ist.

Ich möchte eine Klasse erstellen, die @ habc.ABCMeta als Metaklasse und ist sowohl mit Python 2.7 als auch mit Python 3.5 kompatibel. Bisher ist mir dies nur mit 2.7 oder 3.5 gelungen - jedoch nie mit beiden Versionen gleichzeitig. Könnte mir jemand helfen?

Python 2.7:

import abc
class SomeAbstractClass(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def do_something(self):
        pass

Python 3.5:

import abc
class SomeAbstractClass(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def do_something(self):
        pass
Teste

Wenn wir den folgenden Test mit der geeigneten Version des Python-Interpreters ausführen (Python 2.7 -> Beispiel 1, Python 3.5 -> Beispiel 2), ist er in beiden Szenarien erfolgreich:

import unittest
class SomeAbstractClassTestCase(unittest.TestCase):
    def test_do_something_raises_exception(self):
        with self.assertRaises(TypeError) as error:
            processor = SomeAbstractClass()
        msg = str(error.exception)
        expected_msg = "Can't instantiate abstract class SomeAbstractClass with abstract methods do_something"
        self.assertEqual(msg, expected_msg)
Proble

Während der Test mit Python 3.5 ausgeführt wird, tritt das erwartete Verhalten nicht auf TypeError wird beim Instanziieren von @ nicht ausgelöSomeAbstractClass):

======================================================================
FAIL: test_do_something_raises_exception (__main__.SomeAbstractClassTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tati/sample_abc.py", line 22, in test_do_something_raises_exception
    processor = SomeAbstractClass()
AssertionError: TypeError not raised

----------------------------------------------------------------------

Wenn der Test mit Python 2.7 ausgeführt wird, wird einSyntaxError:

 Python 2.7 incompatible
 Raises exception:
  File "/home/tati/sample_abc.py", line 24
    class SomeAbstractClass(metaclass=abc.ABCMeta):
                                     ^
 SyntaxError: invalid syntax

Antworten auf die Frage(8)

Ihre Antwort auf die Frage