Reputation: 3
Getters for Python's properties are not callable, for example as a 'key' in list.sort. Is it right to simply use get to use the property as a callable getter method?
import random
class Numbers:
def __init__(self, num):
self._num = num
# getter property is not callable (e.g., in list.sort())
@property
def num(self):
return self._num
def __str__(self):
return str(self._num)
nums = []
print("\nSorted numbers")
nums.sort(key=Numbers.num.__get__) # Error raised without __get__
for n in nums:
print(n, end=' ')
I appreciate if someone would confirm this is the right way or suggest a better way of doing this. Thank you!
Upvotes: 0
Views: 73
Reputation: 782148
Use lambda
, then it doesn't matter whether it's an ordinary attribute or a getter.
nums.sort(key = lambda n: n.num)
Upvotes: 2
Reputation: 532093
You can get access to the property's getter via its fget
attribute.
nums.sort(key=Numbers.num.fget)
It might be simpler, though, to simply provide a __lt__
method that compares Numbers
instances by their _num
attributes:
# Ignoring issues of other not being an instance of Numbers itself...
def __lt__(self, other):
return self._num < other._num
Upvotes: 0