当我将代码库从Python 3.7.5更新到3.10时,我遇到了一些问题.
据我所知,继承应该有从左到右的顺序,这意味着如果你从两个类继承,那么它应该使用左类方法.在Python 3.7.5中也是这样,但是在Python 3.10中,如果你首先继承int或float,然后你向继承列表中添加第二个类(在我的例子中是Base),那么它将使用Base的__str__
方法,而__repr__
方法会按预期工作.
我是不是遗漏了什么?这是个窃听器吗?
class Base:
def __str__(self) -> str:
return 'Base'
def __repr__(self) -> str:
return 'Base'
class Integer(int, Base):
def __new__(cls, value):
return int.__new__(cls, value)
class String(str, Base):
def __new__(cls, value):
return str.__new__(cls, value)
print(f"str: {Integer(2)} and {String(2)}")
print(f"repr: {repr(Integer(2))} and {repr(String(2))}")
在Python3.7.5中,它打印:
str: 2 and 2
repr: 2 and '2'
在Python3.10和3.11中,它打印:
str: Base and 2
repr: 2 and '2'