I’m sure there is a term for what I’m looking for, or if there’s not, there is a very good reason what I’m trying to do is in fact silly.
But anyway. I’m wondering whether there is a (quasi) built-in way of finding a certain class instance that has a property set to a certain value.
An example:
class Klass(object):
def __init__(self, value):
self.value = value
def square_value(self):
return self.value * self.value
>>> a = Klass(1)
>>> b = Klass(2)
>>> instance = find_instance([a, b], value=1)
>>> instance.square_value()
1
>>> instance = find_instance([a, b], value=2)
>>> instance.square_value()
4
I know that I could write a function that loops through all Klass instances, and returns the ones with the requested values. On the other hand, this functionality feels as if it should exist within Python already, and if it’s not, that there must be a very good reasons why it’s not. In other words, that what I’m trying to do here can be done in a much better way.
(And of course, I’m not looking for a way to square a value. The above is just an example of the construct I’m trying to look for).
Use filter:
Filter will return a list of objects which meet the requirement you specify. Docs: http://docs.python.org/library/functions.html#filter
Bascially,
filter(fn, list)iterates overlist, and appliesfnto each item. It collects all of the items for whichfnreturns true, puts then into a list, and returns them.NB: filter will always return a list, even if there is only one object which matches. So if you only wanted to return the first instance which matches, you’d have to to something like:
or, better yet,
Then, you would call this function like this:
and then
instancewould bea.