首页 > 解决方案 > Python中可变性和不变性的机制是什么?

问题描述

我是 Python 的新手(自从我第一次开始学习它以来已经 2 天了),但我在 C 方面已经有了一定的经验,当我的教授告诉我整数和其他数据类型时,我正在学习可变性和不变性在 Python 中是不可变的。他通过将 int 分配给变量、显示内存地址、修改变量并再次显示其中已修改的内存地址来证明这一点。

我开始对此进行试验,并发现以下内容:

>>> a = 5
>>> id(a)
140708610844592 
>>> a = 6
>>> id(a)
140708610844624
>>> # jumps 32 bits
>>> a = 5
>>> id(a)
140708610844592
>>> #Same address 'a' declared the first time
>>> b = 5
>>> id(b)
140708610844592
>>> #Same address as a
>>> c = [3,4,5,6]
>>> id(c)
2168086594816
>>> id(c[2]) #index of 5
140708610844592
>>> #same address for 5 but memory not contiguous data type 'list' is a pointer?
>>> c = [3,4,5,6]
>>> id(c)
2168086406272
>>> #Even though list is the same, memory changes which is not happening for int
>>> x = 7
>>> id(x)
140708610844656
>>> 140708610844656 - 140708610844624 #address of 'x' minus address of when 'a' was 6
32
>>> # mem in 6 and 7 are contiguous
>>> id(8) #Value not declared before
140708610844688
>>> 140708610844688 - 140708610844656 #address of 8 minus address of x
32
>>> # x and 8 are contiguous, ints pre-declared?
>>> z = (3,4,5,6) #tuple
>>> id(z)
2168086643872
>>> id(z[2])
140708610844592 #Always same location for int 5
>>> z = (3,4,5,6)
>>> id(z)
2168086750288 #same tuple sequence, different address, same happened with list
>>> id(100)
140708610847632
>>> 140708610847632 - 140708610844592 #Address in 100 minus address in 5
3040
>>> 3040/32 #number of bits between size of int
95.0 # between 5 and 100 exist 95 consecutive ordered ints
>>> st = "hello"
>>> id(st)
2168086495280
>>> id(st[0]) #address of character 'h'
2168051747440
>>> st = "hell"
>>> id(st)
2168086498416
>>> id(st[0])
2168051747440
>>> st = "hello"
>>> id(st)
2168086498352
>>> id(st[0])
2168051747440 #address of 'h' remains the same but str 'hello' address different

因此,基于此,我的问题很明显。

整数和其他字符是否已经预定义并且变量只是根据这些值分配了它们的内存地址?

即使声明了相同的序列,元组、str、列表的内存地址也会不断变化。

因此,从我的角度来看,如果我们认为在重新定义时更改地址的每种数据类型都是不可变的,那么实际上每个数据类型变量都是不可变的,除了预定义的整数和字符,它们基本上不会改变它们在内存中的位置。

因此,包含 int 元素的列表与元组一样不可变。

还是可变性/不变性仅指是否可以修改序列中的元素,如果 int 它既不是可变的,也不是不可变的,因为它是一个对象本身,而不是一个序列。

而且,数据类型列表、元组等只是指向其他地址的指针?与数组不同,它们的元素似乎并不在一起,而是在不同的位置,就像链表一样。

我希望你们能帮助我澄清这一点。

标签: pythonlistmemorytuplesimmutability

解决方案


推荐阅读