0

上下文

我有一个具有相对复杂的类层次结构的 python 应用程序。它需要与 python 2.6 到 python 3.5 一起工作(范围很大,我知道!),而且我在 ABC 方面遇到了特别的问题。我正在使用six图书馆with_metaclass来减轻一些伤害,但这仍然是个问题。

一组特定的课程给我带来了麻烦。以下是它的简化形式:

from abc import ABCMeta
from six import with_metaclass

# SomeParentABC is another ABC, in case it is relevant
class MyABC(with_metaclass(ABCMeta, SomeParentABC)):
    def __init__(self, important_attr):
        self.important_attr = important_attr
    def gamma(self):
         self.important_attr += ' gamma'

class MyChild1(MyABC):
    def __repr__(self):
        return "MyChild1(imporant_attr=%s)" % important_attr
    def alpha(self):
         self.important_attr += ' alpha'

class MyChild2(MyABC):
    def __repr__(self):
        return "MyChild2(imporant_attr=%s)" % important_attr
    def beta(self):
         self.important_attr += ' beta'

gamma捆绑了很多类似的函数MyABC,以及一些特定于子类的函数,例如alphabeta。我希望所有的子类都MyABC继承相同的__init__gamma属性,然后堆放在自己的特定特征上。

问题

问题是,为了MyChild1MyChild2共享代码__init__MyABC需要有一个具体的初始化程序。在 Python 3 中,一切正常,但在 Python 2 中,当初始化程序具体时,我无法TypeErrors在实例化MyABC.

我的测试套件中有一个部分看起来像这样

def test_MyABC_really_is_abstract():
    try:
        MyABC('attr value')
    # ideally more sophistication here to get the right kind of TypeError,
    # but I've been lazy for now
    except TypeError:
        pass
    else:
        assert False

不知何故,在 Python 2.7(我假设是 2.6,但没有费心检查)这个测试失败了。

MyABC没有任何其他抽象属性,但是实例化一个没有 or 的类是没有gamma意义alphabeta。目前,我只是通过复制and中的__init__函数来解决 DRY 违规问题,但随着时间的推移,这变得越来越繁重。MyChild1MyChild2

如何在不使其可实例化的情况下为 Python 2 ABC 提供具体的初始化程序,同时保持 Python 3 的兼容性?换句话说,我想尝试在 Python 2 和 Python 3 中实例化MyABCthrow TypeErrors,但它只在 Python 3 中抛出它们。

with_metaclass

我相信在这里查看代码是相关的with_metaclass。这是根据six项目的现有许可和版权提供的,(c) 2010-2014 Bejamin Peterson

def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    # This requires a bit of explanation: the basic idea is to make a dummy
    # metaclass for one level of class instantiation that replaces itself with
    # the actual metaclass.
    class metaclass(meta):
        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)
    return type.__new__(metaclass, 'temporary_class', (), {})
4

1 回答 1

2

元类在six.with_metaclass()覆盖时可能与 ABC 不兼容type.__new__;这可能会干扰测试具体方法的正常程序。

尝试使用@six.add_metaclass()类装饰器

from abc import ABCMeta from 6 import add_metaclass

@add_metaclass(ABCMeta)
class MyABC(SomeParentABC):
    def __init__(self, important_attr):
        self.important_attr = important_attr
    def gamma(self):
         self.important_attr += ' gamma'

演示:

>>> from abc import ABCMeta, abstractmethod
>>> from six import add_metaclass
>>> @add_metaclass(ABCMeta)
... class MyABC(object):
...     @abstractmethod
...     def gamma(self): pass
... 
>>> MyABC()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyABC with abstract methods gamma

请注意,您确实需要有没有具体实现的抽象方法TypeError才能提出!

于 2014-08-09T17:47:11.297 回答