Python:单行中的多个作业如何工作? [英] Python: How does multiple assignments in a single line work?

查看:132
本文介绍了Python:单行中的多个作业如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个赋值是Python中的一个语句,也就是说,它不像一个表达式那样评估一个值。那么以下代码行在Python中如何工作呢?请解释Python解释器内部发生的事情(词法,解析,抽象语法树的形成)。

 #这个工程
spam = eggs ='ham'

#这不行。抛出SyntaxError
spam =(eggs ='ham')


解决方案>


为什么上面的第一行工作,而第二行不行?


这不是关于运算符优先。这是一个指定的语法。它不能通过加括号进行重新调用。



现在,完整的答案(如@ Rob的评论已经指出),请参阅 here here


I know that assignment is a statement in Python, i.e., it doesn't evaluate to a value unlike an expression. How does the following line of code work in Python, then? Please explain what happens internally in the Python interpreter (lexing, parsing, formation of abstract syntax tree).

# this works
spam = eggs = 'ham'

# this doesn't work. Throws SyntaxError
spam = (eggs = 'ham')

解决方案

why the first line above works while the second doesn't?

It's not about operator precedence. It's a designated syntax. It cannot be "reconcilliated" by adding parenthesis.

Now for the full answer (as @Rob's comments already indicate) see here and here.

这篇关于Python:单行中的多个作业如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆