gpt4 book ai didi

python - 需要帮助理解 python 语法

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:19 24 4
gpt4 key购买 nike

谁能解释一下第 5 行和第 16 行的语法

   1 # Using the generator pattern (an iterable)
2 class firstn(object):
3 def __init__(self, n):
4 self.n = n
5 self.num, self.nums = 0, []
6
7 def __iter__(self):
8 return self
9
10 # Python 3 compatibility
11 def __next__(self):
12 return self.next()
13
14 def next(self):
15 if self.num < self.n:
16 cur, self.num = self.num, self.num+1
17 return cur
18 else:
19 raise StopIteration()
20
21 sum_of_first_n = sum(firstn(1000000))

最佳答案

这就是元组赋值;您可以分配给多个目标。

首先计算右侧的表达式,然后将该序列中的每个值从左到右逐个分配给左侧的名称。

因此,self.num, self.nums = 0, []0 赋值给self.num[] self.nums

参见 assigment statements documentation :

  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

因为右侧部分执行,行 cur, self.num = self.num, self.num+1 赋给 self .nu​​m to cur after 计算self.num + 1,赋值给self.num。如果 self.num 在该行之前为 5,则在该行之后 cur5,并且 self.num 是 6.

关于python - 需要帮助理解 python 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com