我尝试写一个小班,想根据重量对物品进行排序。提供代码,
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
。这里有什么问题?
原文由 Arefe 发布,翻译遵循 CC BY-SA 4.0 许可协议
正是它所说的:
sort
不接受任何位置参数。它采用名为key
的仅关键字参数:从 文档 中:
签名中的
*
是位置参数和关键字参数之间的分隔符;它作为初始“参数”的位置表明缺少位置参数。