gpt4 book ai didi

python - 覆盖 Python 中的比较方法

转载 作者:行者123 更新时间:2023-11-28 22:13:36 25 4
gpt4 key购买 nike

我从我的一个 friend 那里看到这段代码。它是对 Python 中覆盖比较方法的测试。当我运行代码时,我得到了这个:

正确

正确

正确

还有这个:“类型错误:‘A’和‘B’的实例之间不支持‘<’”

如果是这样,为什么“a1 == b1”没有发生同样的错误?

class A:
def __init__(self, x):
self.x = x
class B:
def __init__(self, x):
A.__init__(self, x)
def __eq__(self, other):
return self.x == other.x
def __lt__(self, other):
return self.x < other.x
a1 = A(1)
b1 = B(1)
print(b1 == a1)
print(a1 == b1)

a2 = A(2)
b2 = B(1)
print(b2 < a2)

a3 = A(1)
b3 = B(2)
print(a3 < b3)

最佳答案

你需要定义__lt__在类里面A也是:

class A:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return self.x < other.x
class B(A):
def __init__(self, x):
A.__init__(self, x)
def __eq__(self, other):
return self.x == other.x
def __lt__(self, other):
return self.x < other.x
a1 = A(1)
b1 = B(1)
print(b1 == a1)
print(a1 == b1)

a2 = A(2)
b2 = B(1)
print(b2 < a2)

a3 = A(1)
b3 = B(2)
print(a3 < b3)

当然,其他运营商也是如此。发生这种情况的原因是因为在b < a调用的方法是 B.__lt__a < b调用的方法是 A.__lt__ .定义了前一种方法,但未定义后者。

顺便说一句,你调用 AB 中的构造函数的构造函数。我假设你想要一个 B也是A , 所以 B继承自 A .这就是为什么我的代码说 class B(A) 的原因.

关于python - 覆盖 Python 中的比较方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com