Python 基于属性迭代对象列表

Python 基于属性迭代对象列表,python,python-2.7,iteration,Python,Python 2.7,Iteration,我知道这可能是重复的,但我找不到解决我问题的答案 我的班级定义如下: 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_idlen

我知道这可能是重复的,但我找不到解决我问题的答案

我的班级定义如下:

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
我想做的是,根据
get\u idless()
的返回值,使用for循环或任何使用iterable对象的函数,例如
numpy.mean()
或内置的
max()
min()
,迭代
Destination
对象列表 我已尝试将
\uuuu iter\uuuu()
添加为:

    def __iter__(self):
        yield self.get_idleness()
但当我尝试此示例时,输出不正确:

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

编辑:我意识到我的问题不清楚。我的最终目标是在遍历
目的地的列表时使用
self.get_idless()
返回的值。这样,无论采用何种迭代方法,我都会根据更大的空闲值来比较目的地。

我认为您有点困惑。如果您有一个
Destination
对象列表,并且希望获得(比如)其中的最大空闲时间,您可以使用:

dests = [] # Your list of Destination objects
for i in range(6):
    dests.append(Destination(name="wp%s" % i))

maxIdleness = max( [d.get_idleness() for d in dests] )
您需要目的地列表中的
max
(或
min
mean
或其他内容),因此您需要创建一个新列表。您还可以事先创建列表,并将其重新用于多个计算,这将更加有效:

idlenessList = [d.get_idleness() for d in dests]
maxIdleness = max(idlenessList)
minIdleness = min(idlenessList)
如果您仍然需要让类返回自定义的
min
max
值,以下问题可能会对您有所帮助:


还要注意,代码中有一个错误,访问
\uu idless
时不应使用括号,因为它是一个属性而不是函数:

    def get_idleness(self):
        now = time.time()
        return now - self.__idleness # not self.__idleness()
max(dests, key=Destination.get_idleness)

如果需要基于对象的
get\u idle
min
max
对象,可以通过指定
函数来实现:

    def get_idleness(self):
        now = time.time()
        return now - self.__idleness # not self.__idleness()
max(dests, key=Destination.get_idleness)

那么您的问题是什么呢?您已经为type
Destination
定义了
\uuu iter\uuu
,但是您在type
列表[Destination]
上调用了
max
!它不像你想象的那样运行。在这种情况下,
max
将使用
Destination.\uuu\lt\uuu
来查找最大的项。您的意思是希望对象在迭代器中使用时被直接解释为空闲?那可能是个坏主意。如果只想循环一组目的地,为什么?需要时最好使用
map
max(map(Destination.get\u idless,some\u destinations))
而且您的类型实际上是不可排序的,因为它没有定义任何比较方法。
max(dests)
之所以有效,是因为您使用的是Python2,它在对不可排序的对象进行排序时具有良好的性能。在Python3上,您将得到一个错误。您的澄清仍然不清楚。迭代和比较是两件根本不同的事情--
max
恰好两者都做。那么,您的目标是迭代还是比较?