为什么Python中没有“++”操作?

2024-04-26 05:09:38 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Why there are no ++ and — operators in Python?

这个问题可能看起来很奇怪,但我想知道为什么Python中没有这样的操作。

我知道,x += 1几乎和{}一样简单,但仍然如此。在我熟悉的大多数语言中都有这样的操作(C,C++,爪哇,C,JavaScript,PHP),但是Python中没有。 也许这和这种语言的系统论有关?在


Tags: andnoin语言javascriptarephpthere
3条回答

避免前增量、后增量的混淆,保持简单。在

同样,诸如intlong这样的数据类型是不可变的。++--运算符的含义是更改当前数据类型。因此不支持。在

在增量操作之后,python对象本身会发生变化。在

>>> a = int(10)
>>> b = a
>>> print id(a), id(b)
166744132 166744132
>>> a += 1
>>> print id(a), id(b)
166744120 166744132
>>> print a, b
11 10

重复问题如下,其中包含更多信息:

Why are there no ++ and --​ operators in Python?

Behaviour of increment and decrement operators in Python

报价单PEP-20

There should be one – and preferably only one – obvious way to do it.

您提到的所有语言都继承了C的运算符,在C语言中指针算法的广泛使用使得递增和递减操作更加常见。使用速记并不能提高Python的表达能力,除了“C做到了”之外,实际上没有其他理由将其添加到语言中。(这本身并不是一个很有力的理由。)

虽然与Python没有直接关系,但请看一下:

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

简而言之,是的,这是一个语言设计的决定。在

相关问题 更多 >

    热门问题