I know this is probably duplicate, but I couldn't find an answer that could solve my issue.
My class is defined as follows:
import time
class Destination(object):
def __init__(self, name):
self.name = name
self.__idleness = time.time()
# keeps track of the time value when object was created
def get_idleness(self):
now = time.time()
return now - self.__idleness
What I want to do is to iterate a list of Destination
objects based on the return value of get_idleness()
, either with a for loop or with any function that uses an iterable object, for example numpy.mean()
or built-in max()
and min()
.
I have tried adding the __iter__()
as:
def __iter__(self):
yield self.get_idleness()
but when I tried this example, output was incorrect:
dests = []
for i in range(6):
dests.append(Destination(name="wp%s" % i))
time.sleep(1)
print max(dests)
for d in dests:
print "%s: %s" % (d.name, d.get_idleness())
# max(dests): wp1
# printing all the values shows that wp0 should be the correct return value
EDIT: I realize my question was unclear. My end goal would be to use the value returned by self.get_idleness()
when iterating over a list of Destination
s. That way, no matter the iterating method, I'd compare the Destinations based on the greater idleness value.