Reputation: 184
New to python so forgive me if this is obvious.
Say I've created a custom class Foo
, and make a list of Foo() instances mixed with int
s, for example:
foo_list = [Foo() for _ in range(10)]
for i in range(10):
foo_list.append(i)
# then the foo_list is mixed with Foo()s and ints
How can a Foo
instance be comparable with an int
? Basically my target is to make it possible to sort()
the above list.
Upvotes: 1
Views: 781
Reputation: 32294
You can add __lt__
and __gt__
methods to the Foo
class (less than and greater than) that evaluate Foo
objects as being less than or greater than integers, this is used by sort
when a key function is not provided
class Foo():
def __lt__(self, other):
if isinstance(other, int):
return self._id < other
elif isinstance(other, self.__class__):
return self._id < other._id
def __gt__(self, other):
if isinstance(other, int):
return self._id > other
elif isinstance(other, self.__class__):
return self._id > other._id
Upvotes: 1
Reputation: 330
You can specify a custom function for the python sort()
function, see the "key" function in the docs for the sorting function.
As an example, if Foo
has an integer-like field bar
, you could sort each instance of a Foo
by the value of its bar
with this:
def custom_key_function(element):
if isinstance(element, Foo):
return element.bar
else:
return element # element is just an int
foo_list.sort(key=custom_key_function)
Note the use of isinstance
, which will tell you whether something is an instance of a Foo
.
I don't know what fields your Foo
has, but as long as your custom_key_function
transforms a Foo
into something that can be compared with an int
you should be good.
Upvotes: 1