除了 int
之外,还有哪些具有 __index__()
方法的 Python 对象示例?
例如,Hex文档状态:
If
x
is not a Python int object, it has to define an__index__()
method that returns an integer.
这是为了自学。
最佳答案
大多数情况下,这些都是来自数学库的类型,例如 NumPy或SymPy 。这些库有自己的整数类型(有充分的理由),但由于 __index__
,它们的特殊整数可以用作列表索引或像普通整数一样传递给 hex
。
In [9]: import sympy
In [10]: x = sympy.Integer(1)
In [11]: x # It looks like a regular 1, but it's not.
Out[11]: 1
In [12]: x/2 # This object has special behavior that makes sense for SymPy...
Out[12]: 1/2
In [13]: [1, 2, 3][x] # but you can still use it for things like indexing.
Out[13]: 2
关于python - 具有 __index__() 方法的 Python 对象示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38572999/