2024-05-23 13:27:06 发布
网友
Possible Duplicate:Behaviour of increment and decrement operators in Python
我对python完全陌生,我编写了++x,以为它会增加x,所以我错了,没问题。但也没有语法错误。因此我的问题是:在python中,++x实际上意味着什么?在
+运算符是unary plus operator;它返回其数值参数不变。因此++x被解析为+(+(x)),并给出{}不变(只要x包含一个数字):
+
++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将如上所述引发。在
TypeError
为了确认这一点,我们可以使用ast module来演示Python如何解析表达式:
+
运算符是unary plus operator;它返回其数值参数不变。因此++x
被解析为+(+(x))
,并给出{x
包含一个数字):如果对用户定义类的对象调用} special method 存在,则将调用它;否则,
+
,则如果^{TypeError
将如上所述引发。在为了确认这一点,我们可以使用ast module来演示Python如何解析表达式:
^{pr2}$相关问题 更多 >
编程相关推荐