gpt4 book ai didi

python - 为什么 python 2 中整数缺少一些特殊方法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:27:13 24 4
gpt4 key购买 nike

在 python 2 或 3 中,内置类具有显式定义的特殊方法。 Explicit is better than implicit以及所有爵士乐。

5. > 4.
# True
(5.).__ge__(4.)
# True

但在 python 2 中,某些方法有异常(exception),至少在整数方面是这样。

5 > 4
# True
(5).__ge__(4)
# AttributeError: 'int' object has no attribute '__ge__'
# But not all of them fail!
(5).__add__(4)
# 9

这种行为背后的原因是什么?为什么要这样设计?

我使用的是Python 2.7.12

最佳答案

data model 已更新 。在 可以使用 __cmp__ method :

object.__cmp__(self, other)

Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity ("address"). See also the description of __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by __cmp__() has been removed since Python 1.5.)

(已添加格式)

丰富的比较运算符是 __le__ , __ge__ , etc. 。所以在 还有一个额外的后备机制。这是为 int 定义的,如您所见:

>>> (2).__cmp__
<method-wrapper '__cmp__' of int object at 0x13ee140>
>>> (2).__cmp__(3)
-1

(Python 2.7.12)

此外 提供 cmp(..) builtin function :

cmp(x, y)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

(已添加格式)

, __cmp__已被删除,您可以在 What’s New In Python 3.0 中看到:

The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

(已添加格式)

此机制不仅仅是 __cmp__ 的包装器:它会首先查看是否有丰富的比较,如果没有则回退到 __cmp__本身。

关于python - 为什么 python 2 中整数缺少一些特殊方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43048083/

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