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

2 comments:

  1. hello friend Ive seen on stackoverflow that you had a problem in python with: Q : How can I change the attribute of everything in a whole directory structure?

    Have you solved it?can you help me too?:(
    I wont take much of your time
    hope you have some free time to help me
    this is my email: jqkker22ro@yahoo.com
    Wish you a great day !

    ReplyDelete