为什么BatchIndices对象不是迭代器?

时间:2018-04-05 05:29:39

标签: python-2.7 iterator

以下是代码:

class BatchIndices(object):

    def __init__(self, n, bs, shuffle=False):
        self.n,self.bs,self.shuffle = n,bs,shuffle
        print(n,bs)
        self.lock = threading.Lock()
        self.reset()

    def reset(self):
        self.idxs = (np.random.permutation(self.n) 
                 if self.shuffle else np.arange(0, self.n))
        self.curr = 0

    def __next__(self):
        with self.lock:
        if self.curr >= self.n: self.reset()
            ni = min(self.bs, self.n-self.curr)
            res = self.idxs[self.curr:self.curr+ni]
            self.curr += ni
            print(res)
            return res
bi = BatchIndices(5,3, True)
[next(bi) for o in range(5)]

错误:

Traceback (most recent call last)
<ipython-input-26-7f3487846737> in <module>()
  1 bi = BatchIndices(5,3, True)
----> 2 [next(bi) for o in range(5)]

TypeError: BatchIndices object is not an iterator

我不知道为什么&#39; BatchIndices&#39;对象不是迭代器,甚至是类BatchIndices中的next()对象

1 个答案:

答案 0 :(得分:0)

这是Python 2.您需要__next__,因为在Python 3中引入了import threading import numpy as np class BatchIndices(object): def __init__(self, n, bs, shuffle=False): self.n,self.bs,self.shuffle = n,bs,shuffle print(n,bs) self.lock = threading.Lock() self.reset() def reset(self): self.idxs = (np.random.permutation(self.n) if self.shuffle else np.arange(0, self.n)) self.curr = 0 def __next__(self): with self.lock: if self.curr >= self.n: self.reset() ni = min(self.bs, self.n-self.curr) res = self.idxs[self.curr:self.curr+ni] self.curr += ni print(res) return res next = __next__ bi = BatchIndices(5,3, True) [next(bi) for o in range(5)]

(5, 3)

输出:

resetPin: function(callback) {
    let user = Meteor.users.findOne({ username: "8390883758" });
    let data = Accounts.sendResetPasswordEmail(user._id);
    let token = user.services.password.reset.token;
    return token;
}