______返回超类而不是子类的实例

问题描述 投票:1回答:1

[当我将某个类作为子类时,说int,并自定义它的__add__方法并调用super().__add__(other),它将返回int的实例,而不是我的子类。我可以通过在返回type(self)的每个方法的每个super()调用之前添加int来解决此问题,但这似乎过多。必须有更好的方法来做到这一点。 floatsfractions.Fraction也会发生相同的情况。

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

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

输出:<class 'int'>

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

python python-3.x overloading subclass
1个回答
0
投票

当从int派生时,它不会更改所有内置方法。我会尝试这样更明确:

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

x = A()
print(type(x + 1))
© www.soinside.com 2019 - 2024. All rights reserved.