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 variableself.__weight = weightdef weight(self):return self.__weightdef __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)
When I run the program, I get the error stack of Python TypeError: sort() takes no positional arguments
. Whats the issue here?
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())
From the 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.
[...]
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.