pythonの参照とコピー


#!/usr/bin/env python
# fileencoding=utf-8

import copy

class obj(object):
instance = None
item = [1,2,3,4,5,6]
def __init__(self): pass
def append(self, arg):
self.item.append(arg)
def getInstance(self):
if self.instance == None:
self.instance = obj()
return self.instance


class Example:
o = None
def __init__(self):
self.o = obj().getInstance()
def getObj(self):
return self.o.item
def getShallowCopy(self):
return copy.copy(self.o.item)
def getDeepCopy(self):
return copy.deepcopy(self.o.item)

if __name__ == "__main__":
e = Example()
x = e.getObj()
y = e.getShallowCopy()
z = e.getDeepCopy()
print(x, y, z)
e.o.append(7)
e.getObj().append(8)
print(x, y, z)
x.append(9)
print(e.getObj())

で実行結果。


([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6])
([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

copyを使用してないメソッドは参照渡しされてますね。

以前prototypeの実装したときにcopyを使うべきだったな。