abc.ABCMeta
,并且可以同时兼容Python 2.7和Python 3.5。到目前为止,我只能在2.7或3.5上成功创建,但从未在两个版本上同时成功。有人可以帮我吗?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
测试
如果我们使用适当版本的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运行测试时,期望的行为没有发生(即在实例化SomeAbstractClass
时未引发TypeError
):
======================================================================
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
class Test(with_metaclass(abc.ABCMeta, object)):
。 - sam-6174