python2.7和3.5相互兼容吗,以与Python 2.7和Python 3.5兼容的方式使用abc.ABCMeta

I'd like to create a class which has abc.ABCMeta as a metaclass and is compatible both with Python 2.7 and Python 3.5. Until now, I only succeeded doing this either on 2.7 or on 3.5 - but never on both versions simultaneously. Could someone give me a hand?

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

Testing

If we run the following test using the suitable version of the Python interpreter (Python 2.7 -> Example 1, Python 3.5 -> Example 2), it succeeds in both scenarios:

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)

Problem

While running the test using Python 3.5, the expected behavior doesn't happen (TypeError is not raised while instantiating 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

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

Whereas running the test using Python 2.7 raises a SyntaxError:

Python 2.7 incompatible

Raises exception:

File "/home/tati/sample_abc.py", line 24

class SomeAbstractClass(metaclass=abc.ABCMeta):

^

SyntaxError: invalid syntax

解决方案import abc, six

@six.add_metaclass(abc.ABCMeta)

class SomeAbstractClass():

@abc.abstractmethod

def do_something(self):

pass

six is a Python 2 and 3 compatibility library. You can install it by running pip install six or by downloading the latest version of six.py to your project directory.

For those of you who prefer future over six, the relevant function is future.utils.with_metaclass.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值