我想创建一个具有abc.ABCMeta
元类并且与 Python 2.7 和 Python 3.5 兼容的类。到目前为止,我只在 2.7 或 3.5 上成功地做到了这一点——但从来没有同时在两个版本上。有人可以帮我一把吗?
蟒蛇 2.7:
import abc
class SomeAbstractClass(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def do_something(self):
pass
蟒蛇 3.5:
import abc
class SomeAbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def do_something(self):
pass
测试
如果我们使用合适版本的 Python 解释器(Python 2.7 -> 示例 1,Python 3.5 -> 示例 2)运行以下测试,它在两种情况下都成功:
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)
问题
使用 Python 3.5 运行测试时,没有发生预期的行为(TypeError
实例化时不会引发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
----------------------------------------------------------------------
而使用 Python 2.7 运行测试会引发SyntaxError
:
Python 2.7 incompatible
Raises exception:
File "/home/tati/sample_abc.py", line 24
class SomeAbstractClass(metaclass=abc.ABCMeta):
^
SyntaxError: invalid syntax