Best way to receive the 'return' value from a python generator

后端 未结 4 1755
慢半拍i
慢半拍i 2020-12-15 03:15

Since Python 3.3, if a generator function returns a value, that becomes the value for the StopIteration exception that is raised. This can be collected a number of ways:

4条回答
  •  -上瘾入骨i
    2020-12-15 03:30

    The most obvious method I can think of for this would be a user defined type that would remember the summary for you..

    >>> import random
    >>> class ValueProducer:
    ...    def produce_values(self, n):
    ...        self._total = 0
    ...        for i in range(n):
    ...           r = random.randrange(n*100)
    ...           self._total += r
    ...           yield r
    ...        self.value_summary = self._total/n
    ...        return self.value_summary
    ... 
    >>> v = ValueProducer()
    >>> for i in v.produce_values(3):
    ...    print(i)
    ... 
    25
    55
    179
    >>> print(v.value_summary)
    86.33333333333333
    >>> 
    

提交回复
热议问题