gpt4 book ai didi

python - 是否可以在 python 中重载多重比较语法?

转载 作者:太空狗 更新时间:2023-10-29 20:45:59 25 4
gpt4 key购买 nike

我想知道是否可以在 python 中重载多重比较语法:

a < b < c

我知道可以重载单个比较,是否可以重载这些比较?

最佳答案

在内部它被处理为a < b and b < c , 所以你只需要重载 __lt__ , __gt__

来自docs :

x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

>>> import dis
>>> dis.dis(lambda : a < b < c)
1 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (b)
6 DUP_TOP
7 ROT_THREE
8 COMPARE_OP 0 (<)
11 JUMP_IF_FALSE_OR_POP 21
14 LOAD_GLOBAL 2 (c)
17 COMPARE_OP 0 (<)
20 RETURN_VALUE
>> 21 ROT_TWO
22 POP_TOP
23 RETURN_VALUE

演示:

class A(object):
def __lt__(self, other):
print 'inside lt'
return True
def __gt__(self, other):
print 'inside gt'
return True
...
>>> a = A()
>>> 10 < a < 20
inside gt
inside lt
True

关于python - 是否可以在 python 中重载多重比较语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17197953/

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