简体   繁体   English

需要帮助理解python语法

[英]Need help understanding python syntax

Can someone explain the syntax on lines 5 & 16 有人可以解释第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))

That's tuple assignment; 这是元组任务; you can assign to multiple targets. 您可以分配给多个目标。

The right-hand expression is evaluated first, and then each value in that sequence is assigned to the names on left-hand side one by one, from left to right. 首先评估右侧表达式,然后将该序列中的每个值从左到右依次分配给左侧的名称。

Thus, self.num, self.nums = 0, [] assigns 0 to self.num and [] to self.nums . 因此, self.num, self.nums = 0, []受让人0self.num[]self.nums

See the assigment statements documentation : 请参阅assigment statements文档

  • 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. 如果目标列表是以逗号分隔的目标列表:对象必须是具有与目标列表中的目标相同数量的项目的可迭代项,并且项目将从左到右分配给相应的目标。

Because the right-hand side portion is executed first , the line cur, self.num = self.num, self.num+1 assigns self.num to cur after calculating self.num + 1 , which is assigned to self.num . 因为首先执行右侧部分,所以行cur, self.num = self.num, self.num+1 计算self.num + 1 后将 self.num + 1 self.numcur ,该值被分配给self.num If self.num was 5 before that line, then after that line cur is 5 , and self.num is 6. 如果self.num在该行之前是5 ,那么在该行之后cur5 ,并且self.num是6。

self.num, self.nums = 0, []
cur, self.num = self.num, self.num+1

These are shorthands for the following: 这些是以下方面的缩写:

self.num = 0
self.nums = []

and

cur = self.num
self.num = self.num + 1

As a personal preference, I would not use the compound assignments in either of these two lines. 作为个人偏好,我不会在这两行中的任何一行中使用复合赋值。 The assignments are not related, so there's no reason to combine them. 分配不相关,因此没有理由将它们组合在一起。

There are times when compound assignments can prove useful. 有时候复合分配可以证明是有用的。 Consider how one swaps two numbers in languages like C and Java: 考虑如何在C和Java等语言中交换两个数字:

temp = a
a = b
b = temp

In Python we can eliminate the temporary variable! 在Python中我们可以消除临时变量!

a, b = b, a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM