Python 类型错误 : sort() takes no positional arguments

标签 python python-3.x class sorting arguments

我尝试写一个小类,想根据重量对元素进行排序。提供代码,

class Bird:

    def __init__(self, weight):
        # __weight for the private variable
        self.__weight = weight

    def weight(self):
        return self.__weight

    def __repr__(self):
        return "Bird, weight = " + str(self.__weight)


if __name__ == '__main__':

    # Create a list of Bird objects.
    birds = []
    birds.append(Bird(10))
    birds.append(Bird(5))
    birds.append(Bird(200))

    # Sort the birds by their weights.
    birds.sort(lambda b: b.weight())

    # Display sorted birds.
    for b in birds:
        print(b)

当我运行程序时,我得到错误堆栈 Python TypeError: sort() takes no positional arguments。这里有什么问题?

最佳答案

正是它所说的:sort不接受任何位置参数。它需要一个名为 key 的仅关键字参数:

birds.sort(key=lambda b: b.weight())

来自documentation :

sort(*, key=None, reverse=False)

This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

[...]

*签名中是位置参数和仅关键字参数之间的分隔符;它作为初始“参数”的位置表明缺少位置参数。

关于Python 类型错误 : sort() takes no positional arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55344116/

相关文章:

python - Python 中的文件处理 : being used by another process

c++ - 类方法中的模板函数指针参数

C++ 访问类对象 vector 中的元素

python - 使用 CSS 选择器和 BeautifulSoup 获取属性值

python - 哪些 2to3 修复程序输出有效的 Python 2 代码?

python - 如何获得 1 :1 corresponding matches using sklearn KNearest neighbors

python检查m个方法中的n个返回值是否为真

c++ - 如何访问属于另一个类的私有(private)成员的类的方法

javascript - 转置列数据并将其复制到每行

jquery - "Best"将 Django 与 Ajax 库集成的方法