这几天我刚学会python。在看书的时候,我发现了一行我不懂的代码。 请参见print_progression()方法下的第46行,print(''.join(str(next(self))for j in range(n)))。在
class Progression:
'''Iterator producing a generic progression.
Default iterator produces the whole number, 0, 1, 2, ...
'''
def __init__(self, start = 0):
'''
Initialize current to the first value of the progression.
'''
self._current = start
def _advance(self):
'''
Update self.current to a new value.
This should be overriden by a subclass to customize progression.
By convension, if current is set to None, this designates the
end of a finite progression.
'''
self._current += 1
def __next__(self):
'''
Return the next element, or else raise StopIteration error.
'''
# Our convention to end a progression
if self._current is None:
raise StopIteration()
else:
# record current value to return
answer = self._current
# advance to prepare for next time
self._advance()
# return the answer
return answer
def __iter__(self):
'''
By convention, an iterator must return itself as an iterator.
'''
return self
def print_progression(self, n):
'''
Print next n values of the progression.
'''
print(' '.join(str(next(self)) for j in range(n)))
class ArithmeticProgression(Progression): # inherit from Progression
pass
if __name__ == '__main__':
print('Default progression:')
Progression().print_progression(10)
'''Output is
Default progression:
0 1 2 3 4 5 6 7 8 9 10'''
我不知道next(self)和j是怎么工作的。在
我想应该是str(前进。下一步()). (已解决)
我哪儿也找不到j。j代表什么?为什么不使用while循环,比如while前进。下一步()<;=范围(n)?
我最后的想法应该是
print('''.join(str(next(self)),而next(self)<;=范围(n)))
救救这个新手。在
提前谢谢!在
我想是@csevieradded a reasonable discussion about your first question,但根据你的评论,我不确定第二个问题的答案是否清晰,所以我将尝试另一个角度。在
假设你做了:
这是可以理解的-您创建了一个列表
^{pr2}$[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
,然后依次打印该列表中的每个值。现在假设我们只想打印"hello"
10次;我们可以非常简单地修改现有代码:但是现在
x
把我们的输出搞乱了。没有:语法。我们可以使用
while
循环,但这意味着要定义一个额外的计数器:那是行李。因此,更好的方法是使用
for x in range(10):
,而不必费心去做print(x)
;这个值是为了让我们的循环工作,而不是因为它实际上在任何其他方面都有用。这对于j
也是一样的(虽然我在我的示例中使用了x
,因为我认为在教程中您更可能遇到它,但是您可以使用任何您想要的名称)。另外,while
循环通常用于可以无限期运行的循环,而不是用于迭代具有固定大小的对象:请参见here。在欢迎来到python社区!这是一个很好的问题。在python中,就像在其他语言中一样,有很多方法来完成任务。但是,当您遵循python社区所遵循的约定时,这通常被称为“python”解决方案。print_progression方法是用户定义的数据结构迭代的常见python解决方案。在上面的例子中,让我们先解释一下代码是如何工作的,然后解释为什么要这样做。在
print_progression方法利用progression类通过实现next和iterdunder/magic方法来实现迭代协议。因为这些都是实现的,所以你可以像next(self)那样在内部迭代类实例,也可以在外部迭代next(Progression()),这正是您在数字1中得到的结果。因为这个协议已经实现了,这个类可以在任何客户端的任何内置迭代器和生成器上下文中使用!这是一种多态性的解决方案。它只是在内部使用,因为你不需要用两种不同的方法。在
现在是未使用的J变量。他们只是使用它,以便可以使用for循环。仅仅使用range(n)将只返回一个ITETRABLE,但不会对其进行迭代。我不太同意作者使用名为J的变量,通常更常见的是表示一个未使用的变量,因为它需要作为一个单独的下划线使用。我更喜欢这个:
相关问题 更多 >
编程相关推荐