上下文
我有一个具有相对复杂的类层次结构的 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
,以及一些特定于子类的函数,例如alpha
和beta
。我希望所有的子类都MyABC
继承相同的__init__
和gamma
属性,然后堆放在自己的特定特征上。
问题
问题是,为了MyChild1
和MyChild2
共享代码__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
意义alpha
的beta
。目前,我只是通过复制and中的__init__
函数来解决 DRY 违规问题,但随着时间的推移,这变得越来越繁重。MyChild1
MyChild2
如何在不使其可实例化的情况下为 Python 2 ABC 提供具体的初始化程序,同时保持 Python 3 的兼容性?换句话说,我想尝试在 Python 2 和 Python 3 中实例化MyABC
throw TypeError
s,但它只在 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', (), {})