问题:为什么Python中没有++和-运算符?

为什么在Python中没有++and --运算符?

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


回答 0

不是因为它没有道理;而是因为它没有意义。最好将“ x ++”定义为“ x + = 1,求出x的先前绑定”。

如果您想知道最初的原因,则必须要么浏览旧的Python邮件列表,要么询问那里的某个人(例如Guido),但是在事实成立之后就很容易找到理由了:

与其他语言一样,不需要简单的增量和减量。您不会for(int i = 0; i < 10; ++i)经常用Python 编写东西。相反,你做类似的事情for i in range(0, 10)

由于几乎不需要它,因此没有太多理由为其提供特殊的语法。当您确实需要增加时,+=通常就可以了。

这不是是否有意义,还是可以做到的决定。这是一个好处是否值得添加到该语言的核心语法中的问题。请记住,这是四个运算符-postinc,postdec,preinc,predec,并且每个运算符都需要具有自己的类重载;他们都需要指定和测试;它将在语言中添加操作码(暗示更大,因此更慢的VM引擎);每个支持逻辑增量的类都需要实现它们(在+=和之上-=)。

+=和都是多余的-=,因此将成为净亏损。

It’s not because it doesn’t make sense; it makes perfect sense to define “x++” as “x += 1, evaluating to the previous binding of x”.

If you want to know the original reason, you’ll have to either wade through old Python mailing lists or ask somebody who was there (eg. Guido), but it’s easy enough to justify after the fact:

Simple increment and decrement aren’t needed as much as in other languages. You don’t write things like for(int i = 0; i < 10; ++i) in Python very often; instead you do things like for i in range(0, 10).

Since it’s not needed nearly as often, there’s much less reason to give it its own special syntax; when you do need to increment, += is usually just fine.

It’s not a decision of whether it makes sense, or whether it can be done–it does, and it can. It’s a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators–postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of += and -=).

This is all redundant with += and -=, so it would become a net loss.


回答 1

我写的这个原始答案是关于计算机民俗的一个神话:被丹尼斯·里奇(Dennis Ritchie)认为是“历史上不可能的”,正如ACM通讯编辑在2012年7月致函doi:10.1145 / 2209249.2209251


C增/减运算符是在C编译器不是很聪明的时候发明的,作者希望能够指定使用机器语言运算符的直接意图,从而节省了编译器的几个周期,可能会做一个

load memory
load 1
add
store memory

代替

inc memory 

PDP-11甚至支持分别对应于*++p和的“自动递增”和“延迟自动递增”指令*p++。如果非常好奇,请参阅手册第5.3节。

由于编译器足够聪明,可以处理C语法中内置的高级优化技巧,因此它们现在只是语法上的便利。

Python没有技巧来向汇编器传达意图,因为它不使用汇编器。

This original answer I wrote is a myth from the folklore of computing: debunked by Dennis Ritchie as “historically impossible” as noted in the letters to the editors of Communications of the ACM July 2012 doi:10.1145/2209249.2209251


The C increment/decrement operators were invented at a time when the C compiler wasn’t very smart and the authors wanted to be able to specify the direct intent that a machine language operator should be used which saved a handful of cycles for a compiler which might do a

load memory
load 1
add
store memory

instead of

inc memory 

and the PDP-11 even supported “autoincrement” and “autoincrement deferred” instructions corresponding to *++p and *p++, respectively. See section 5.3 of the manual if horribly curious.

As compilers are smart enough to handle the high-level optimization tricks built into the syntax of C, they are just a syntactic convenience now.

Python doesn’t have tricks to convey intentions to the assembler because it doesn’t use one.


回答 2

我一直以为这与python禅的这一行有关:

应该有一种(最好只有一种)明显的方式来做到这一点。

x ++和x + = 1做完全相同的事情,因此没有理由同时使用两者。

I always assumed it had to do with this line of the zen of python:

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

x++ and x+=1 do the exact same thing, so there is no reason to have both.


回答 3

当然,我们可以说“圭多岛就是这样决定的”,但我认为问题实际上是做出该决定的原因。我认为有以下几个原因:

  • 它将陈述和表达式混合在一起,这不是一个好习惯。参见http://norvig.com/python-iaq.html
  • 它通常会鼓励人们编写可读性较低的代码
  • 如前所述,语言实现的额外复杂性在Python中是不必要的

Of course, we could say “Guido just decided that way”, but I think the question is really about the reasons for that decision. I think there are several reasons:

  • It mixes together statements and expressions, which is not good practice. See http://norvig.com/python-iaq.html
  • It generally encourages people to write less readable code
  • Extra complexity in the language implementation, which is unnecessary in Python, as already mentioned

回答 4

因为在Python中,整数是不可变的(int的+ =实际上返回了一个不同的对象)。

同样,使用++ /-时,您需要担心增量前后的递增和递减,并且只需要再写一次按键即可x+=1。换句话说,它避免了潜在的混乱,但付出的代价却很小。

Because, in Python, integers are immutable (int’s += actually returns a different object).

Also, with ++/– you need to worry about pre- versus post- increment/decrement, and it takes only one more keystroke to write x+=1. In other words, it avoids potential confusion at the expense of very little gain.


回答 5

明晰!

Python有很多关于清晰度--a的知识,除非他/她学习了具有这种构造的语言,否则任何程序员都不可能正确地猜测的含义。

Python还有很多关于避免引发错误的构造的知识,并且++已知运算符是缺陷的丰富来源。这两个原因足以在Python中没有这些运算符。

Python使用缩进来标记块而不是诸如某种形式的开始/结束方括号或强制结束标记之类的句法手段的决定很大程度上基于相同的考虑。

作为说明,请看一下有关在2005年向Python中引入条件运算符(在C:中cond ? resultif : resultelse)的讨论。至少请阅读该讨论第一条消息决策消息(之前有相同主题的多个先驱)。

琐事: 其中经常提到的PEP是“ Python扩展建议” PEP 308。LC表示列表理解,GE表示生成器表达式(不要担心,如果它们使您感到困惑,它们不是Python的少数复杂地方)。

Clarity!

Python is a lot about clarity and no programmer is likely to correctly guess the meaning of --a unless s/he’s learned a language having that construct.

Python is also a lot about avoiding constructs that invite mistakes and the ++ operators are known to be rich sources of defects. These two reasons are enough not to have those operators in Python.

The decision that Python uses indentation to mark blocks rather than syntactical means such as some form of begin/end bracketing or mandatory end marking is based largely on the same considerations.

For illustration, have a look at the discussion around introducing a conditional operator (in C: cond ? resultif : resultelse) into Python in 2005. Read at least the first message and the decision message of that discussion (which had several precursors on the same topic previously).

Trivia: The PEP frequently mentioned therein is the “Python Extension Proposal” PEP 308. LC means list comprehension, GE means generator expression (and don’t worry if those confuse you, they are none of the few complicated spots of Python).


回答 6

我对python为什么没有++运算符的理解如下:当您在python中编写此代码时,a=b=c=1您将获得三个变量(标签),它们指向同一对象(值为1)。您可以使用id函数进行验证,该函数将返回对象内存地址:

In [19]: id(a)
Out[19]: 34019256

In [20]: id(b)
Out[20]: 34019256

In [21]: id(c)
Out[21]: 34019256

所有三个变量(标签)都指向同一对象。现在递增变量之一,看看它如何影响内存地址:

In [22] a = a + 1

In [23]: id(a)
Out[23]: 34019232

In [24]: id(b)
Out[24]: 34019256

In [25]: id(c)
Out[25]: 34019256

您可以看到该变量a现在指向另一个对象,为bc。因为您已经使用a = a + 1它,所以它很明显。换句话说,您将另一个对象完全分配给label a。想象一下,您可以编写a++它,这表明您没有分配给变量a新对象,而是增加了旧对象的数量。所有这些东西都是恕我直言,以尽量减少混乱。为了更好地理解,请参见python变量如何工作:

在Python中,为什么函数可以修改调用者认为的某些参数,而不能修改其他参数?

Python是按值调用还是按引用调用?都不行

Python是按值传递还是按引用传递?

Python是按引用传递还是按值传递?

Python:如何通过引用传递变量?

了解Python变量和内存管理

在python中模拟按值传递行为

Python函数通过引用调用

像Pythonista一样的代码:惯用的Python

My understanding of why python does not have ++ operator is following: When you write this in python a=b=c=1 you will get three variables (labels) pointing at same object (which value is 1). You can verify this by using id function which will return an object memory address:

In [19]: id(a)
Out[19]: 34019256

In [20]: id(b)
Out[20]: 34019256

In [21]: id(c)
Out[21]: 34019256

All three variables (labels) point to the same object. Now increment one of variable and see how it affects memory addresses:

In [22] a = a + 1

In [23]: id(a)
Out[23]: 34019232

In [24]: id(b)
Out[24]: 34019256

In [25]: id(c)
Out[25]: 34019256

You can see that variable a now points to another object as variables b and c. Because you’ve used a = a + 1 it is explicitly clear. In other words you assign completely another object to label a. Imagine that you can write a++ it would suggest that you did not assign to variable a new object but ratter increment the old one. All this stuff is IMHO for minimization of confusion. For better understanding see how python variables works:

In Python, why can a function modify some arguments as perceived by the caller, but not others?

Is Python call-by-value or call-by-reference? Neither.

Does Python pass by value, or by reference?

Is Python pass-by-reference or pass-by-value?

Python: How do I pass a variable by reference?

Understanding Python variables and Memory Management

Emulating pass-by-value behaviour in python

Python functions call by reference

Code Like a Pythonista: Idiomatic Python


回答 7

它就是这样设计的。递增和递减运算符只是的快捷方式x = x + 1。Python通常采用了一种设计策略,该策略减少了执行操作的替代方法的数量。 增量分配是Python中最接近递增/递减运算符的东西,直到Python 2.0才添加。

It was just designed that way. Increment and decrement operators are just shortcuts for x = x + 1. Python has typically adopted a design strategy which reduces the number of alternative means of performing an operation. Augmented assignment is the closest thing to increment/decrement operators in Python, and they weren’t even added until Python 2.0.


回答 8

我是python的新手,但我怀疑原因是由于该语言中的可变对象和不可变对象之间的强调。现在,我知道x ++可以很容易地解释为x = x + 1,但是它看起来就像您就地递增一个不可变的对象一样。

只是我的猜测/感觉/预感。

I’m very new to python but I suspect the reason is because of the emphasis between mutable and immutable objects within the language. Now, I know that x++ can easily be interpreted as x = x + 1, but it LOOKS like you’re incrementing in-place an object which could be immutable.

Just my guess/feeling/hunch.


回答 9

首先,Python仅受C间接影响。它在很大程度上受到影响ABC,这显然不具备这些运营商,所以它不应该有任何巨大的惊喜不会找到它们在Python两种。

其次,正如其他人所说,递增和递减由支持+=-=了。

第三,对++and --运算符集的完全支持通常包括同时支持它们的前缀和后缀版本。在C和C ++中,这可能导致各种“可爱”的构造(在我看来)与Python所包含的简单性和直截了当的精神背道而驰。

例如,尽管C语句while(*t++ = *s++);对于有经验的程序员而言似乎简单而优雅,但对于学习它的人来说,却绝非简单。混合使用前缀和后缀增量和减量,甚至许多专业人士也必须停下来思考一下。

First, Python is only indirectly influenced by C; it is heavily influenced by ABC, which apparently does not have these operators, so it should not be any great surprise not to find them in Python either.

Secondly, as others have said, increment and decrement are supported by += and -= already.

Third, full support for a ++ and -- operator set usually includes supporting both the prefix and postfix versions of them. In C and C++, this can lead to all kinds of “lovely” constructs that seem (to me) to be against the spirit of simplicity and straight-forwardness that Python embraces.

For example, while the C statement while(*t++ = *s++); may seem simple and elegant to an experienced programmer, to someone learning it, it is anything but simple. Throw in a mixture of prefix and postfix increments and decrements, and even many pros will have to stop and think a bit.


回答 10

我认为这源于Python的信条,即“明确胜于隐含”。

I believe it stems from the Python creed that “explicit is better than implicit”.


回答 11

这可能是因为@GlennMaynard正在将问题与其他语言进行比较,但是在Python中,您是以python方式进行操作的。这不是一个“为什么”的问题。在那里,您可以使用达到相同的效果x+=。在《 Python的禅宗》中,给出了:“只有一种解决问题的方法。” 多种选择在艺术上(表达自由)很棒,但在工程上却很​​糟糕。

This may be because @GlennMaynard is looking at the matter as in comparison with other languages, but in Python, you do things the python way. It’s not a ‘why’ question. It’s there and you can do things to the same effect with x+=. In The Zen of Python, it is given: “there should only be one way to solve a problem.” Multiple choices are great in art (freedom of expression) but lousy in engineering.


回答 12

++运算符的类别是具有副作用的表达式。这是Python中通常找不到的东西。

出于同样的原因,赋值不是Python中的表达式,因此防止了通用 if (a = f(...)) { /* using a here */ }用法。

最后,我怀疑操作符与Python的参考语义不是很一致。请记住,Python没有具有C / C ++已知语义的变量(或指针)。

The ++ class of operators are expressions with side effects. This is something generally not found in Python.

For the same reason an assignment is not an expression in Python, thus preventing the common if (a = f(...)) { /* using a here */ } idiom.

Lastly I suspect that there operator are not very consistent with Pythons reference semantics. Remember, Python does not have variables (or pointers) with the semantics known from C/C++.


回答 13

也许更好的问题是问为什么这些运算符存在于C中。K&R调用增量和减量运算符为“异常”(第2.8页第2.8节)。导言称它们“更简洁,通常更高效”。我怀疑这些操作总是在指针操作中出现的事实也影响了它们的引入。在Python中,可能已经决定尝试优化增量没有任何意义(事实上,我只是在C中进行了测试,而且似乎gcc生成的程序集在两种情况下都使用addl而不是incl),并且没有指针算法;因此,它本来只是另一种实现方式,而我们知道Python不愿这样做。

Maybe a better question would be to ask why do these operators exist in C. K&R calls increment and decrement operators ‘unusual’ (Section 2.8page 46). The Introduction calls them ‘more concise and often more efficient’. I suspect that the fact that these operations always come up in pointer manipulation also has played a part in their introduction. In Python it has been probably decided that it made no sense to try to optimise increments (in fact I just did a test in C, and it seems that the gcc-generated assembly uses addl instead of incl in both cases) and there is no pointer arithmetic; so it would have been just One More Way to Do It and we know Python loathes that.


回答 14

据我了解,所以您不会认为内存中的值已更改。在c中,当执行x ++时,内存中x的值会更改。但是在python中,所有数字都是不可变的,因此x指向的地址仍然具有x而不是x + 1。当您编写x ++时,您可能会认为x发生了改变,实际上是x引用更改为x + 1存储在内存中的位置,或者如果doe不存在,则重新创建该位置。

as i understood it so you won’t think the value in memory is changed. in c when you do x++ the value of x in memory changes. but in python all numbers are immutable hence the address that x pointed as still has x not x+1. when you write x++ you would think that x change what really happens is that x refrence is changed to a location in memory where x+1 is stored or recreate this location if doe’s not exists.


回答 15

要在该页面上完成已经很好的答案:

假设我们决定这样做,在前缀(++i)处打乱一元+和-运算符。

今天,以++--做任何前缀都没有,因为它使一元加号运算符两次(不执行任何操作)或一元减号两次(两次:取消自身)成为可能

>>> i=12
>>> ++i
12
>>> --i
12

这样可能会破坏这种逻辑。

To complete already good answers on that page:

Let’s suppose we decide to do this, prefix (++i) that would break the unary + and – operators.

Today, prefixing by ++ or -- does nothing, because it enables unary plus operator twice (does nothing) or unary minus twice (twice: cancels itself)

>>> i=12
>>> ++i
12
>>> --i
12

So that would potentially break that logic.


回答 16

其他答案描述了为什么迭代器不需要它,但是有时在分配以增加内联变量时它很有用,您可以使用元组和多重分配来达到相同的效果:

b = ++a 变成:

a,b = (a+1,)*2

b = a++成为:

a,b = a+1, a

Python的3.8引入了分配:=操作,使我们能够实现foo(++a)

foo(a:=a+1)

foo(a++) 虽然仍然难以捉摸。

Other answers have described why it’s not needed for iterators, but sometimes it is useful when assigning to increase a variable in-line, you can achieve the same effect using tuples and multiple assignment:

b = ++a becomes:

a,b = (a+1,)*2

and b = a++ becomes:

a,b = a+1, a

Python 3.8 introduces the assignment := operator, allowing us to achievefoo(++a) with

foo(a:=a+1)

foo(a++) is still elusive though.


回答 17

我认为这涉及对象的可变性和不可变性的概念。2,3,4,5在python中是不可变的。请参考下图。2具有固定的ID,直到此python进程为止。

常量和变量的ID

x ++本质上意味着像C的就地增量。在C中,x ++执行就地增量。因此,x = 3,并且x ++会将内存中的3增加到4,这与python中内存中仍然存在3的情况不同。

因此,在python中,您无需在内存中重新创建值。这可能会导致性能优化。

这是基于预感的答案。

I think this relates to the concepts of mutability and immutability of objects. 2,3,4,5 are immutable in python. Refer to the image below. 2 has fixed id until this python process.

ID of constants and variables

x++ would essentially mean an in-place increment like C. In C, x++ performs in-place increments. So, x=3, and x++ would increment 3 in the memory to 4, unlike python where 3 would still exist in memory.

Thus in python, you don’t need to recreate a value in memory. This may lead to performance optimizations.

This is a hunch based answer.


回答 18

我知道这是一个旧线程,但是没有涵盖++ i的最常见用例,即在没有提供索引的情况下手动索引集。这就是为什么python提供enumerate()的原因

示例:在任何给定的语言中,当您使用诸如foreach之类的结构来遍历一个集合时,出于示例的考虑,我们甚至会说它是无序的集合,并且您需要一个唯一的索引来区分所有内容,例如

i = 0
stuff = {'a': 'b', 'c': 'd', 'e': 'f'}
uniquestuff = {}
for key, val in stuff.items() :
  uniquestuff[key] = '{0}{1}'.format(val, i)
  i += 1

在这种情况下,python提供了一个枚举方法,例如

for i, (key, val) in enumerate(stuff.items()) :

I know this is an old thread, but the most common use case for ++i is not covered, that being manually indexing sets when there are no provided indices. This situation is why python provides enumerate()

Example : In any given language, when you use a construct like foreach to iterate over a set – for the sake of the example we’ll even say it’s an unordered set and you need a unique index for everything to tell them apart, say

i = 0
stuff = {'a': 'b', 'c': 'd', 'e': 'f'}
uniquestuff = {}
for key, val in stuff.items() :
  uniquestuff[key] = '{0}{1}'.format(val, i)
  i += 1

In cases like this, python provides an enumerate method, e.g.

for i, (key, val) in enumerate(stuff.items()) :

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。