简体   繁体   English

Python 3中的__int__和__index__方法有什么区别?

[英]What is the difference between the __int__ and __index__ methods in Python 3?

The Data Model section of the Python 3.2 documentation provides the following descriptions for the __int__ and __index__ methods: Python 3.2文档的Data Model部分提供了__int____index__方法的以下描述:

object.__int__(self)

Called to implement the built-in [function int() ]. 被调用来实现内置的[function int() ]。 Should return [an integer]. 应该返回[整数]。

object.__index__(self)

Called to implement operator.index() . 被调用来实现operator.index() Also called whenever Python needs an integer object (such as in slicing, or in the built-in bin() , hex() and oct() functions). 每当Python需要一个整数对象时(例如在切片中,或在内置bin()hex()oct()函数中) oct()调用。 Must return an integer. 必须返回一个整数。

I understand that they're used for different purposes, but I've been unable to figure out why two different methods are necessary. 我知道它们用于不同的目的,但我一直无法弄清楚为什么需要两种不同的方法。 What is the difference between these methods? 这些方法有什么区别? Is it safe to just alias __index__ = __int__ in my classes? 在我的课程中只是别名__index__ = __int__是否安全?

See PEP 357 : Allowing Any Object to be Used for Slicing. 请参阅PEP 357 :允许任何对象用于切片。

The nb_int method is used for coercion and so means something fundamentally different than what is requested here. nb_int方法用于强制,因此意味着与此处要求的根本不同的东西。 This PEP proposes a method for something that can already be thought of as an integer communicate that information to Python when it needs an integer. 这个PEP提出了一种方法, 可以将其视为一个整数,当需要一个整数时,将该信息传递给Python。 The biggest example of why using nb_int would be a bad thing is that float objects already define the nb_int method, but float objects should not be used as indexes in a sequence. 使用nb_int的原因最大的一个例子是float对象已经定义了nb_int方法,但float对象应该用作序列中的索引。

Edit : It seems that it was implemented in Python 2.5. 编辑 :它似乎是在Python 2.5中实现的。

I believe you'll find the answer in PEP 357 , which has this abstract: 我相信你会在PEP 357中找到答案,它有这个摘要:

This PEP proposes adding an nb_index slot in PyNumberMethods and an __index__ special method so that arbitrary objects can be used whenever integers are explicitly needed in Python, such as in slice syntax (from which the slot gets its name). 此PEP建议在PyNumberMethods中添加nb_index槽和__index__特殊方法,以便在Python中显式需要整数时可以使用任意对象,例如切片语法(槽从中获取其名称)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM