[英]Examples of Python Objects That Have An __index__() method?
What are some examples of Python objects that have an __index__()
method other than an int
? 除了int
以外,还具有__index__()
方法的Python对象的一些示例是什么?
For example, the Hex documentation state: 例如, 十六进制文档状态:
If
x
is not a Python int object, it has to define an__index__()
method that returns an integer. 如果x
不是Python int对象,则它必须定义一个返回整数的__index__()
方法。
This is for self-learning. 这是用于自学。
Mostly, these are types from mathematical libraries like NumPy or SymPy . 通常,这些是来自NumPy或SymPy等数学库的类型。 These libraries have their own integer types (for good reason), but thanks to __index__
, their special integers can be used as list indices or passed to hex
like normal integers. 这些库具有自己的整数类型(有充分的理由),但是由于使用__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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.