简体   繁体   English

具有__index __()方法的Python对象示例?

[英]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 . 通常,这些是来自NumPySymPy等数学库的类型。 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.

相关问题 Python __index__特殊方法 - Python __index__ special method Python - 切片索引必须是整数或无或具有 __index__ 方法 - Python - slice indices must be integers or None or have an __index__ method Python string.find()给出错误“切片索引必须为整数或无,或具有__index__方法” - Python string.find() giving error “slice indices must be integers or None or have an __index__ method” 在 Python 中使用字符串作为切片索引? (类型错误:切片索引必须是整数或无或具有 __index__ 方法) - Use strings as slice indices in Python ? (TypeError: slice indices must be integers or None or have an __index__ method) TypeError:切片索引必须为整数或无,或具有__index__方法python - TypeError: slice indices must be integers or None or have an __index__ method python Python TypeError:切片索引必须是整数或无或具有 __index__ 方法 - Python TypeError: slice indices must be integers or None or have an __index__ method Python 3.x-无法修复错误:“切片索引必须为整数或None或具有__index__方法” +更多 - Python 3.x - Cannot fix error: “slice indices must be integers or None or have an __index__ method” + more (python 错误代码)切片索引必须是整数或 None 或具有 __index__ 方法 - (python error code) slice indices must be integers or None or have an __index__ method typeerror slice索引必须为整数或不为整数,或具有__index__方法 - typeerror slice indices must be integers or none or have an __index__ method 切片索引必须为整数或无,或具有__index__方法 - Slice indices must be integers or None or have __index__ method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM