Python TypeError:sort()不接受任何位置参数 [英] Python TypeError: sort() takes no positional arguments

查看:1592
本文介绍了Python TypeError:sort()不接受任何位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写一个小类,并希望根据重量对项目进行排序.提供了代码,

I try to write a small class and want to sort the items based on the weight. The code is provided,

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.这里有什么问题?

When I run the program, I get the error stack of Python TypeError: sort() takes no positional arguments. Whats the issue here?

推荐答案

确切地说:sort不接受任何位置参数.它使用名为key的纯关键字参数:

Exactly what it says: sort doesn't take any positional arguments. It takes a keyword-only argument named key:

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

文档:

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

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()接受两个只能通过关键字传递的参数 (仅关键字参数):

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

key 指定一个参数的功能,该参数用于从每个列表元素(例如,key=str.lower)提取比较键.列表中与每个项目相对应的键仅计算一次,然后用于整个排序过程.默认值None表示列表项直接排序,而无需计算单独的键值.

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.

[...]

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

The * in the signature is the separator between positional parameters and keyword-only parameters; its position as the initial "argument" indicates the lack of positional parameters.

这篇关于Python TypeError:sort()不接受任何位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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