Help!!! Why is there a difference in both cases | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help!!! Why is there a difference in both cases

https://code.sololearn.com/cayc94R0iXUs/?ref=app

7th Apr 2020, 5:54 AM
Aapka Chaihta
Aapka Chaihta - avatar
6 Answers
+ 3
Assignment in Python does not copy anything, it just takes a name sticker and sticks it onto an object. Such a name sticker is called 'reference'. If you try this... obj3 = python() obj4 = obj3.var print(id(obj3.var), id(obj4)) ... you see that both names, obj3.var and obj4, point to the same data. In first example, obj1 and obj2 are two references to the same thing, an attribute of a specific instance, which means that 'var' is exactly the same reference (that attribute) in both cases. So if you reassign var in there, the name sticker is stuck onto a fresh tuple - in both objects, because they're actually only one. In second example, the name obj4 is another reference to obj3.var, but this reference is not sitting *in* that instance but in main module. So when you reassign it, only one changes, because you reassign a name in the global sphere, not in obj3. Nice, confusing example! 😅 More details to figure out these kind of things in here: https://code.sololearn.com/c89ejW97QsTN/?ref=app
7th Apr 2020, 6:36 AM
HonFu
HonFu - avatar
+ 4
My guess is: In case one, you are actually changing the obj.var, which changes value inside class In second case, you store obj.var into a local variable and change value of that local variable which does not affect obj.var variable in any ways.
7th Apr 2020, 6:01 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
https://code.sololearn.com/c1J17z4BZpo5/?ref=app copying a class means to copy the reference to class. copying a tuple means to create a new tuple.
7th Apr 2020, 6:05 AM
Oma Falk
Oma Falk - avatar
+ 2
My brain doesn't work so well with that sort of image, but... well, I think it looks like what I explained. 😅🤔🤣
7th Apr 2020, 8:28 AM
HonFu
HonFu - avatar
+ 1
Guys do I have to think like this???😅 Case 1: https://ibb.co/m4cv3wR Case 2: https://ibb.co/X4tNf61 In case 1: the red arrow is made to point to another location And in case 2 the green arrow. Please correct me if I am wrong. 😅
7th Apr 2020, 7:13 AM
Aapka Chaihta
Aapka Chaihta - avatar
+ 1
The difference is in the first case is still doing reference to the same object but I the second one obj4 only has the referen to value that was assignment, that means that no affect the instance of obj1 or obj3. I'm practicing English.
8th Apr 2020, 3:35 AM
Jonathan Alvarado
Jonathan Alvarado - avatar