为什么 Python 赋值不返回值? [英] Why does Python assignment not return a value?

查看:53
本文介绍了为什么 Python 赋值不返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Python 赋值是语句而不是表达式?如果它是一个返回赋值右侧值的表达式,则在某些情况下它会允许更少冗长的代码.有什么我看不到的问题吗?

Why is Python assignment a statement rather than an expression? If it was an expression which returns the value of the right hand side in the assignment, it would have allowed for much less verbose code in some cases. Are there any issues I can't see?

例如:

# lst is some sequence
# X is come class
x = X()
lst.append(x)

可以改写为:

lst.append(x = X())

好吧,准确地说,上面的方法不起作用,因为 x 将被视为关键字参数.但是另一对括号(或关键字参数的另一个符号)可以解决这个问题.

Well, to be precise, the above won't work because x would be treated as a keyword argument. But another pair of parens (or another symbol for keyword arguments) would have resolved that.

推荐答案

有很多人认为赋值是表达式,尤其是在 Python 等语言中,any 值在条件中是允许的(不是只是某种布尔类型的值),容易出错.据推测,Guido 就是/曾经有这种感觉的人之一.经典错误是:

There are many who feel that having assignments be expressions, especially in languages like Python where any value is allowable in a condition (not just values of some boolean type), is error-prone. Presumably Guido is/was among those who feel that way. The classic error is:

if x = y: # oops! meant to say ==

在 Python 中的情况也比在像 C 这样的语言中复杂一些,因为在 Python 中,对变量的第一个赋值也是它的声明.例如:

The situation is also a bit more complicated in Python than it is in a language like C, since in Python the first assignment to a variable is also its declaration. For example:

def f():
    print x

def g():
    x = h()
    print x

在这两个函数中,print x"行做了不同的事情:一个指向全局变量x,另一个指向局部变量x.由于赋值,g 中的 x 是本地的.如果可以将赋值隐藏在一些更大的表达式/语句中,这可能会更令人困惑(比现在更混乱).

In these two functions the "print x" lines do different things: one refers to the global variable x, and the other refers to the local variable x. The x in g is local because of the assignment. This could be even more confusing (than it already is) if it was possible to bury the assignment inside some larger expression/statement.

这篇关于为什么 Python 赋值不返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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