I came across code something like this and am trying to understand how it works. From the python documentation for sorted() the key
parameter takes a function which takes a single argument and then returns a key to be used in the comparison. This code is assigning key
a class. How is this ok? And how does __lt__
get x
and y
passed to it?
class K(str):
def __lt__(x, y):
return x > y
input = [3, 30, 7]
sorted(input, key=K)
Output: [7, 30, 3]
python uses duck typing, so it doesn't check if the key is a function, it just calls it. the key argument is used in sorted to determine what to compare. In this case, instead of comparing [3, 30, 7] it's comparing [K(3), K(30), K(7)]. That's also why there's a __lt__ method implemented, for the less than comparison
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.