3 分鐘閱讀

Python 可變物件與不可變物件

python的物件被分為

  1. 可變物件
  2. 不可變物件

當你對可變物件修改值時,不會改變物件本身的記憶體

對不可變物件修改時,會直接產生新的物件並賦予新的記憶體

可變物件

  1. list
  2. set
  3. dict
  4. class

Set Example

s = set([1,2,3])
print(id(s))
def change(s):
    print(id(s))
    s.remove(1)
    print(id(s))

change(s)
print(id(s))

output

1495543984864
1495543984864
1495543984864
1495543984864

去修改時也不會影響Set的記憶體

不可變物件

  1. int
  2. string
  3. float
  4. tupple

Int Example

c = 1
print(id(c))

def count(c):
    print(id(c))
    c += 1
    print(id(c))
count(c)
print(id(c))

output 

2660491094320
2660491094320
2660491094352
2660491094320

可以看到第二個output ID還是一樣

不過只要修改過後,ID就不同了

本來的c也不會受影響

標籤:

更新時間: