自定义类中的Python生成器

2024-05-18 07:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,我试图弄明白为什么自定义类中包含“yield”语句的函数不能按预期运行。我的目标是让函数充当生成器;也就是说,它返回一个生成器迭代器,然后可以在for语句中使用该迭代器

该类定义如下:

class inclusive_range:

    def __init__(self, num):
        self._start = 0
        self._step = 1
        self._stop = num
        self._next = self._start

    # iterator implementation - would like to avoid this
    # def __iter__(self):
    #     return self
    #
    # def __next__(self):
    #     if self._next > self._stop:
    #         raise StopIteration
    #     else:
    #         _r = self._next
    #         self._next += self._step
    #         return _r

    # generator implementation - trying to get this to work
    def generator(self):
        if self._next < self._stop:
            _r = self._next
            self._next += self._step
            yield _r

在主程序中运行此语句时,迭代器实现(注释掉)按预期工作:

for i in inclusive_range(10):
   print(i)

其中输出为预期值(打印数字0到10,包括在内)

但是,当我尝试按如下方式使用生成器时:

for i in inclusive_range(10).generator():
   print(i)

输出仅为单个数字0。起初,我认为generator()调用没有像预期的那样返回迭代器,因此我使用调试器进行了调查:

n = inclusive_range(10)

# I pulled up the "evaluate expression" window in the debugger and did the following:

n.generator().__next()__ # prints 0
n.generator().__next()__ # prints 1!
n.generator().__next()__ # prints 2!
n.generator().__next()__ # prints 3!

# ...and so on until StopIteration is raised.

所以我的问题是…它看起来像我在调试器中期望的那样工作,为什么它只返回第一个值呢


Tags: thetoinselffordefsteprange
2条回答

我认为您希望在生成器方法中使用while循环而不是if语句:

# generator implementation - trying to get this to work
def generator(self):
    while self._next <= self._stop:
        _r = self._next
        self._next += self._step
        yield _r

问题源于发电机未正确成型。您将需要一个循环,在更新对象状态以准备yield下一个值时,它是所需的值。简而言之,你只需要在{}中用{}替换你的{}就可以了!此代码适用于我(为了清晰起见,删除了注释代码):

class inclusive_range:
    def __init__(self, num):
        self._start = 0
        self._step = 1
        self._stop = num
        self._next = self._start

    # generator implementation - trying to get this to work
    def generator(self):
        while self._next < self._stop:  # <  while instead of if
            _r = self._next
            self._next += self._step
            yield _r

以及测试:

> for i in inclusive_range(10).generator(): 
    print(i) 
0
1
2
3
4
5
6
7
8
9

快乐编码

相关问题 更多 >