[当我将某个类作为子类时,说int
,并自定义它的__add__
方法并调用super().__add__(other)
,它将返回int
的实例,而不是我的子类。我可以通过在返回type(self)
的每个方法的每个super()
调用之前添加int
来解决此问题,但这似乎过多。必须有更好的方法来做到这一点。 floats
和fractions.Fraction
也会发生相同的情况。
class A(int):
def __add__(self, other):
return super().__add__(other)
x = A()
print(type(x + 1))
输出:<class 'int'>
预期输出:<class '__main__.A'>
当从int派生时,它不会更改所有内置方法。我会尝试这样更明确:
class A(int):
def __add__(self, other):
return A(super().__add__(other))
x = A()
print(type(x + 1))