Pages

Tuesday, September 3, 2013

In python, objects are referred as references

Python uses shallow copy for object copying. If you see this code, The value b.a.val is modified externally.
class A(object):
    def __init__(self):
        self.val = 20
    
class B(object):
    def __init__(self, a):
        self.a = a
    
if __name__ == "__main__":
    a = A()

    b = B(a)
    print b.a.val # 20
    a.val = 40
    print b.a.val # 40
You need to use copy.deepcopy to avoid this pitfall.
from copy import *

class A(object):
    def __init__(self):
        self.val = 20
    
class B(object):
    def __init__(self, a):
        self.a = deepcopy(a)
        
    
if __name__ == "__main__":
    a = A()

    b = B(a)
    
    print b.a.val
    a.val = 40
    print b.a.val