首页 > 解决方案 > __add__ 返回超类的实例而不是子类

问题描述

当我对某个类进行子类int化并自定义它的__add__方法并调用super().__add__(other)它时,它会返回一个实例int,而不是我的子类。我可以通过在每个返回 an 的方法中的每次调用type(self)之前添加来解决这个问题,但这似乎过分了。必须有更好的方法来做到这一点。和s也会发生同样的事情。super()intfloatsfractions.Fraction

class A(int):
    def __add__(self, other):
        return super().__add__(other)

x = A()
print(type(x + 1))

输出:
<class 'int'>

预期输出:
<class '__main__.A'>

标签: pythonpython-3.xoverloadingsubclass

解决方案


这可以使用描述符来完成。以下类使用在类体内实例化该类时具有特殊效果的特殊方法。

class SuperCaller:

    def __set_name__(self, owner, name):
        """Called when the class is defined. owner is the class that's being
        defined. name is the name of the method that's being defined.
        """
        method = getattr(super(owner, owner), name)
        def call(self, other):
            # Note that this self shadows the __set_name__ self. They are two
            # different things.
            return type(self)(method(self, other))
        self._call = call

    def __get__(self, instance, owner):
        """instance is an instance of owner."""
        return lambda other: self._call(instance, other)


class A(int):
    __add__ = SuperCaller()


x = A()
print(type(x + 1))

输出:<class '__main__.A'>


推荐阅读