我知道这可能是重复的,但我找不到解决我问题的答案
我的班级定义如下:
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_idleness()
的返回值来迭代Destination
对象列表,使用for循环或使用iterable对象的任何函数,例如numpy.mean()
或内置的max()
和min()
。
我尝试将__iter__()
添加为:
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
编辑:我意识到我的问题不清楚。我的最终目标是在遍历Destination
列表时使用self.get_idleness()
返回的值。这样,无论采用何种迭代方法,我都会根据更大的空闲值来比较目的地
我觉得你有点困惑。如果您有一个
Destination
对象列表,并且希望获得(比如)其中的最大空闲时间,那么您可以使用:您需要从目的地列表中获取
max
(或min
、mean
或其他内容),因此您需要创建一个新列表。您还可以事先创建列表,并将其重新用于多个计算,这将更加有效:如果仍然要求类返回自定义的
min
或max
值,那么以下问题可能会对您有所帮助: Is there a way to return a custom value for min and max in Python?还要注意,代码中有一个错误,在访问
__idleness
时不应使用括号,因为它是一个属性而不是函数:如果需要基于
get_idleness
的min
或max
对象,可以通过指定key
函数来实现:相关问题 更多 >
编程相关推荐