gpt4 book ai didi

python - 比较不同类型时如何强制 Python 2 引发异常?

转载 作者:太空狗 更新时间:2023-10-30 02:32:16 24 4
gpt4 key购买 nike

在 Python 2.7.2 中将字符串与 int 进行比较看起来非常不一致:

x = '12'; y = 3
print x > y # True
x = 12; y = '3'
print x > y # False

根据 How does Python compare string and int?在 Python 3 中,这些将引发异常。有没有办法让 Python 2 已经这样做了?看着 __future__我不知道是否有这样的功能。

最佳答案

没有。您的选择是:

  • 编写和使用包装类,在不需要的比较时引发。

  • 编写和使用自定义比较函数来代替常用运算符。

  • 使用 MacroPy 之类的东西让您的自定义比较函数不那么难用。

  • 不要依赖这些语义。

  • 比较前预先检查值。

  • 想用 Python 3 就用 Python 3。

关于python - 比较不同类型时如何强制 Python 2 引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331674/

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