在 python 中使用生成器时如何迭代 class 对象?

how can i iterate class objects while using generator in python?

我想比较a和b的2000对,并打印匹配对和them.can的计数任何人帮助我摆脱 it.it 显示此错误 TypeError: 'seq_generator' object is not iterable at line 34

class generator(object):
    def __init__(self,s,start_A,fact_A):
        self.s=s
        self.start_A=start_A
        self.fact_A = fact_A
    def seq_gen_A(self):
        while self.s>0:
           self.gen_A=(self.start_A*self.fact_A)%2147483647
           self.g=self.gen_A
           self.start_A=self.gen_A
           self.bin_A=(bin(self.gen_A)[-16:])
           yield self.bin_A
           self.s=self.s-1
    def next(self):
           for i in self.seq_gen_A():
           return i
def main():
    s=200
    count=0
    a=generator(s,65,16807)
    b=generator(s,8921,48271)
    print("Matching pair")
    print("*************")
    for i in range(0,s):
        if next(a)==next(b):
           count+=1
           print(a,b)
    print('Matching pair count',count)

您没有正确定义生成器。您需要方法 __iter____next__:

class generator(object):
    def __init__(self, s, start_A, fact_A):
        self.s = s
        self.start_A = start_A
        self.fact_A = fact_A

    def __iter__(self):
        return self

    def __next__(self):
        if self.s <= 0:
            raise StopIteration()
        gen_A = (self.start_A*self.fact_A)%2147483647
        self.start_A = gen_A
        yield bin(gen_A)[-16:]
        self.s -= 1