>>> charles = {'name': 'Charles L. Dodgson', 'born': 1832} >>> lewis = charles >>> lewis is charles True >>> id(charles) 139996185268800 >>> id(lewis) 139996185268800
2.相等性的例子python
>>> charles = {'name': 'Charles L. Dodgson', 'born': 1832} >>> alex = {'name': 'Charles L. Dodgson', 'born': 1832} >>> alex == charles True >>> alex is charles False >>> id(alex) 139996185193136 >>> id(charles) 139996185268800
複製列表(或多數內置的可變集合)最簡單的方式是使用內置的類型構造方法。app
>>> l1 = [12,123,22,213,222,1221] >>> l2 = list(l1) >>> l2 == l1 True >>> l2 is l1 False
>>> l1 = [3, [66,55,44], (7,8,9)] >>> l2 = l1[:] >>> l1.append(100) >>> l1 [3, [66, 55, 44], (7, 8, 9), 100] >>> l1[1].remove(55) >>> print('l1', l1) l1 [3, [66, 44], (7, 8, 9), 100] >>> print('l2', l2) l2 [3, [66, 44], (7, 8, 9)] >>> l2[1] += [33,22] >>> l2[2] += (10,11) >>> print('l1', l1) l1 [3, [66, 44, 33, 22], (7, 8, 9), 100] >>> print('l2', l2) l2 [3, [66, 44, 33, 22], (7, 8, 9, 10, 11)]
import copy class Bus(object): def __init__(self, passengers=None): if passengers is None: self.passengers = [] if passengers is not None: self.passengers = list(passengers) def drop(self, name): self.passengers.remove(name) def pick(self, name): self.passengers.append(name) bus1 = Bus(['Alice', 'Bill', 'Claire', 'David']) bus2 = copy.copy(bus1) bus3 = copy.deepcopy(bus1) bus1.drop('Bill') bus1.pick('tom') print(bus1.passengers) print(bus2.passengers) print(bus3.passengers) # ------------------------- # bus1 ['Alice', 'Claire', 'David', 'tom'] # bus2 ['Alice', 'Claire', 'David', 'tom'] # bus3 ['Alice', 'Bill', 'Claire', 'David']
淺複製時,bus1和bus2,公用了一個列表對象,這個是可變對象函數