欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

为什么 Python 中列表的 sort 方法一定要返回 None 而不是排序后的列表?

程序员文章站 2024-01-15 12:03:10
...
感觉返回None简直反人类嘛,让多少人义无反顾的跳进这个坑中了
sorted无关 就是问返回排序后的列表不是更方便么

回复内容:

一般来说,返回 None 表示是在原对象上进行的操作。返回排序后结果意味着创建了一个副本。

如果你需要返回排序后的,可以使用 sorted 函数。我感觉题主需要的其实是 sorted 函数而非 sort。 这是个好问题,坑过不少人。

1. 从设计角度来说,因为 Command-query separation
Command-query separation states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.

也就是说只有引用透明,也就是没有副作用的函数,才应该具有返回值。

x.sort(),很明显,改变了 x 的值,具有副作用,所以不应该有返回值。

2.从易读性角度来说, Guido van Rossum 在 Python-Dev 邮件列表里也解释过为什么选择将 x.sort() 的返回值定为 None. (邮件原文:[Python-Dev] sort() return value)

3. 从性能和易用性角度来说,Python Doc 解释了为什么要这样设计(Design and History FAQ- List sort)。
In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around.
这并不反人类。

一门编程语言提供了一个sort函数的时候,作为使用者第一个应该问的问题是:这个函数是in-place的还是返回一个新object。Python的sort是in-place的,那么排序完成后的列表就没有返回的必要了,当然返回None是最正确的做法,有什么坑可言? sorted函数和list的sort方法是不一样的

举个简单的例子,dog是一个对象,那dog.bark()应该返回什么?叫完了不就完了嘛,还返回啥。

但是如果有一个函数mated,那mated(dog)应该返回什么?日过的狗,mated_dog。

list.sort()是该list自身调用,list将自身(self)排序(sort)一下,自身(self)发生了改变,而排序这个动作本身是不需要返回什么的,再例如I.eat(apple),难道这个eat还需要返回一个我吗?

而sorted这个函数,是将传入的对象排序返回,这个函数没有什么自身的存在,所以不返回点什么东西,那就没意义了。

总之,这个问题属于面向对象的程序设计,不要用函数式编程的思维硬套。

PS: 以上都是我胡说的,我根本不懂什么面向对象,函数式。 因为当你需要它返回数组时,你写错了。

在你写错的时候可以提醒你,这就是返回空的作用。 让多少人义无反顾地跳坑了?呵呵没多少。 python 还有一个sorted函数
相关标签: sorted None