在Python 2和Python 3中对内置类型进行子类化

khi*_*sen 22 python subclass built-in-types python-3.x

在对内置类型进行子类化时,我注意到内置类型的方法的返回类型中Python 2和Python 3之间存在相当重要的区别.以下代码说明了这些集:

class MySet(set):

    pass

s1 = MySet([1, 2, 3, 4, 5])

s2 = MySet([1, 2, 3, 6, 7])

print(type(s1.union(s2)))

print(type(s1.intersection(s2)))

print(type(s1.difference(s2)))
Run Code Online (Sandbox Code Playgroud)

使用Python 2,所有返回值都是类型MySet.使用Python 3,返回类型是set.我找不到任何关于结果应该是什么的文档,也没有关于Python 3中的更改的任何文档.

无论如何,我真正关心的是:在Python 3中是否有一种简单的方法可以获得Python 2中的行为,而无需重新定义内置类型的每一种方法?

Sve*_*ach 11

在Python 2.x的移动到3.X时,这不是内建类型一般的变化- list和int,例如,在2.x和3.x中相同的行为 只更改了集合类型以使其与其他类型保持一致,如此错误跟踪器问题中所述.

我担心没有什么好方法可以让它表现得很旧.这是我能够提出的一些代码:

class MySet(set):
    def copy(self):
        return MySet(self)
    def _make_binary_op(in_place_method):
        def bin_op(self, other):
            new = self.copy()
            in_place_method(new, other)
            return new
        return bin_op
    __rand__ = __and__ = _make_binary_op(set.__iand__)
    intersection = _make_binary_op(set.intersection_update)
    __ror__ = __or__ = _make_binary_op(set.__ior__)
    union = _make_binary_op(set.update)
    __sub__ = _make_binary_op(set.__isub__)
    difference = _make_binary_op(set.difference_update)
    __rxor__ = xor__ = _make_binary_op(set.__ixor__)
    symmetric_difference = _make_binary_op(set.symmetric_difference_update)
    del _make_binary_op
    def __rsub__(self, other):
        new = MySet(other)
        new -= self
        return new
Run Code Online (Sandbox Code Playgroud)

这将简单地使用返回您自己的类型的版本覆盖所有方法.(有很多方法!)

也许对于您的应用程序,您可以放弃覆盖copy()并坚持就地方法.