Python:默认比较 [英] Python: default comparison

查看:81
本文介绍了Python:默认比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.7中,我定义了一个空的新式样的类:

In Python 2.7, I define an empty new-style class:

In [43]: class C(object): pass
   ....:

然后创建新类的实例列表:

then create a list of instances of the new class:

In [44]: c = [C() for i in xrange(10)]

然后尝试对列表进行排序:

then attempt to sort the list:

In [45]: sorted(c)
Out[45]:
[<__main__.C object at 0x1950a490>,
 <__main__.C object at 0x1950a4d0>,
 ...
 <__main__.C object at 0x1950aad0>]

令人惊讶的是,尽管我没有定义一种比较 C 实例的方法,但是这种排序没有抱怨:

What's surprising is that the sort doesn't complain, even though I haven't defined a way to compare instances of C:

In [46]: dir(C())
Out[46]:
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

$ b $

What exactly is happening there, and what's the rationale for this -- arguably surprising -- behaviour?

推荐答案

我认为唯一的理由是,方便的对象可以排序和例如用作具有某些默认行为的字典键。语言定义中的相关章节位于: https://docs.python .org / 2 / reference / expressions.html#not-in

I think the only rationale is that it is convenient that objects can be sorted and e.g. used as dictionary keys with some default behavior. The relevant chapter in the language definition is here: https://docs.python.org/2/reference/expressions.html#not-in

任意选择一个对象是小于还是大于另一个但是在一个程序的一个执行中是一致的。
"The choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program."

因此,目前对象使用内存地址进行比较的事实只是一个不能计算的实现细节。唯一的保证是,在执行期间,顺序保持一致。

So the fact that objects are currently compared using the memory address is just an implementation detail that cannot be counted upon. The only guarantee is that the ordering stays consistent during execution.

这篇关于Python:默认比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆