我如何使用预递增/递减操作符(++,——),就像在c++ ?
为什么++计数运行,但不改变变量的值?
我如何使用预递增/递减操作符(++,——),就像在c++ ?
为什么++计数运行,但不改变变量的值?
当前回答
虽然其他答案是正确的,因为它们表明了单纯的+通常做什么(即,保持数字的原样,如果它是1),他们是不完整的,因为他们没有解释发生了什么。
确切地说,+ x等于x.__pos__()和+ + x x.__pos__ () .__pos__()。
我可以想象一个非常奇怪的阶级结构(孩子们,不要在家里这样做!),像这样:
class ValueKeeper(object):
def __init__(self, value): self.value = value
def __str__(self): return str(self.value)
class A(ValueKeeper):
def __pos__(self):
print 'called A.__pos__'
return B(self.value - 3)
class B(ValueKeeper):
def __pos__(self):
print 'called B.__pos__'
return A(self.value + 19)
x = A(430)
print x, type(x)
print +x, type(+x)
print ++x, type(++x)
print +++x, type(+++x)
其他回答
++不是运算符。它是两个+运算符。+运算符是单位运算符,它什么也不做。(澄清:+和-一元操作符仅适用于数字,但我假定您不会期望假设的++操作符适用于字符串。)
++count
解析为
+(+count)
翻译过来就是
count
你必须使用稍微长一点的+=运算符来做你想做的事情:
count += 1
我怀疑省略++和——操作符是为了保持一致性和简单性。我不知道Guido van Rossum为这个决定给出的确切理由,但我可以想象出一些理由:
Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist. Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable. Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
虽然其他答案是正确的,因为它们表明了单纯的+通常做什么(即,保持数字的原样,如果它是1),他们是不完整的,因为他们没有解释发生了什么。
确切地说,+ x等于x.__pos__()和+ + x x.__pos__ () .__pos__()。
我可以想象一个非常奇怪的阶级结构(孩子们,不要在家里这样做!),像这样:
class ValueKeeper(object):
def __init__(self, value): self.value = value
def __str__(self): return str(self.value)
class A(ValueKeeper):
def __pos__(self):
print 'called A.__pos__'
return B(self.value - 3)
class B(ValueKeeper):
def __pos__(self):
print 'called B.__pos__'
return A(self.value + 19)
x = A(430)
print x, type(x)
print +x, type(+x)
print ++x, type(++x)
print +++x, type(+++x)
一个直截了当的解决办法
c = 0
c = (lambda c_plusplus: plusplus+1)(c)
print(c)
1
不再打字
c = c + 1
你也可以直接写 c++ 完成所有代码,然后搜索/替换“c++”,替换为“c=c+1”。只要确保正则表达式搜索是关闭的。
python中不像C语言中那样有后/前自增/自减操作符。
我们可以看到++或-作为多个符号相乘,就像我们在数学中做的(-1)*(-1)=(+1)。
E.g.
---count
解析为
-(-(-count)))
翻译过来就是
-(+count)
因为-号和-号的乘法是+
最后,
-count
在Python中,表达式和语句之间有严格的区别 与Common Lisp、Scheme或 Ruby。
维基百科
因此,通过引入这样的操作符,可以打破表达式/语句的分割。
和你不能写作的原因一样
if x = 0:
y = 1
就像在其他一些不保留这种区别的语言中一样。