python如何解析++x?

2024-05-23 13:27:06 发布

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

Possible Duplicate:
Behaviour of increment and decrement operators in Python

我对python完全陌生,我编写了++x,以为它会增加x,所以我错了,没问题。但也没有语法错误。因此我的问题是:在python中,++x实际上意味着什么?在


Tags: andofin语法错误operatorsbehaviourduplicateincrement
1条回答
网友
1楼 · 发布于 2024-05-23 13:27:06

+运算符是unary plus operator;它返回其数值参数不变。因此++x被解析为+(+(x)),并给出{}不变(只要x包含一个数字):

>>> ++5
5
>>> ++"hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

如果对用户定义类的对象调用+,则如果^{} special method存在,则将调用它;否则,TypeError将如上所述引发。在

为了确认这一点,我们可以使用ast module来演示Python如何解析表达式:

^{pr2}$

相关问题 更多 >