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

查看:151
本文介绍了为什么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天全站免登陆