我尝试写一个小类,想根据重量对元素进行排序。提供代码,
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 ofNone
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/