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

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:



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

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

10-12 20:07