Python如何实现自加
先来看一段python代码,如下:
代码示例:
>>>i=1
>>>++i
>>>printi
1
[python]viewplaincopy
>>>i=1
>>>++i
>>>printi
1
以上代码告诉我们,python居然不认识++。
python不使用++的哲学逻辑:编译解析上的简洁与语言本身的简洁。
例子:
代码示例:
>>>b=5
>>>a=5
>>>id(a)
162334512
>>>id(b)
162334512
>>>aisb
True
[python]viewplaincopy
>>>b=5
>>>a=5
>>>id(a)
162334512
>>>id(b)
162334512
>>>aisb
True
说明:
python中,变量是以内容为基准而不是像c中以变量名为基准,所以只要数字内容是5,不管起什么名字,这个变量的ID是相同的,同
时也说明了python中一个变量可以以多个名称访问。
这就决定了python中数字类型的值是不可变的,因为如果如上例,a和b都是5,当你改变了a时,b也会跟着变,这当然不是我们希
望的。
因此,正确的自增操作应该a=a+1或者a+=1,当此a自增后,通过id()观察可知,id值变化了,即a已经是新值的名称。
以上内容为大家介绍了Python如何实现自加,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






