-3

The class is given below, this will print 20_20. Now till the line 5 code is same, I don't want the value of T.a to change when i change value of T1.a. How to solve it?

class Test: 
    def __init__(self, val): 
        self.a = val 

T = Test(10) 
T1 = T 
T1.a = 20 
print T.a + '__' + T1.a

Expected Output Is 10_20 .

simon
  • 2,042
  • 2
  • 20
  • 31
Nitin Kantak
  • 168
  • 9

4 Answers4

5

In line 6. T1 = T, you are telling python to make a new reference to object T called T1.

i dont want the value of T.a to change when i change value of T1.a

This can't be done the way you set it up since T and T1 point to the same object. You can see this by noting that T is T1 evaluates to True in the python interpreter.

It seems maybe that you want to instantiate 2 Test objects, each with its own a property, so that changing one object won't affect the other.

1

The thing you want to do is probably called "deep copying" https://docs.python.org/2/library/copy.html

this allows you to create a copy of an existing object, instead of a reference. That is the closest thing to pass by value, I can think of, when using objects.

Henrik
  • 2,180
  • 16
  • 29
1

You could also use the copy method of the copy module:

import copy
T = Test(20)
T1 = copy.copy(T)
T1.a = 40
print T.a
# Output 20
print T1.a
# Output 40

For more info check out the copy docs, https://docs.python.org/2/library/copy.html

jnishiyama
  • 377
  • 2
  • 8
0

By making T1=T you are making both of them same so if you change T1 it will affect T and vice versa . You could use copy,deep copy etc

class Test: 
    def __init__(self, val): 
        self.a = val 

T = Test (10) 
T1 = Test(20) 
print str(T.a) + '__' + str(T1.a)

see this link for more on mutuable and non-mutable object assignment and value changing

Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65