+ 1
I can't understand pass by reference and pass by value method in python while passing objects. Please Help.
I am from c++ background. Pass by value and pass by reference are pretty clear in c++ because of &operator but in python I am confused how to pass object so that I can change the original object when necessary.
12 Réponses
+ 1
import copy
class node:
def __init__(self,data=None):
self.data = copy.deepcopy(data) #copy
self.next = None
def append(self, data):
if self.data == None:
self.data = copy.deepcopy(data)
return
temp = self
while temp.next != None:
temp = temp.next
temp.next = node(data)
def traverse(self):
temp = self
while temp:
print(temp.data)
temp = temp.next
root = node()
root.append(4)
root.append(9)
root.traverse()
+ 1
In python all is passed by reference.
But there is difference between immutable types and mutable ones.
After passed if the IMMUTABLE type variable is changed, it is copied automatically. So the variable looks as if it were passed by value.
About MUTABLE type, it isn't copied.
So it is only passed by reference.
+ 1
thank you but are user defined objects mutable or immutable ?
+ 1
Immutable: int, float, str, tuple, bytes, frozenset
Mutable : list, dict, set, bytearray
+ 1
But in which category user defined classes fall in ? Mutable or immutable ?
+ 1
It is mutable
+ 1
https://code.sololearn.com/cm2wP8FcgrcV/?ref=app
But here root doesn't get changed in append function. why ?
+ 1
Python : def append(root, data)
|
|
v
c++ : void append(node *root, int data)
the root behaves as a pointer
+ 1
I use double pointer in c++ .
void append(node **root,int data)
hence returning value was not my headache any more.
so I didn't need to return values. So is there something I can do in python ?
+ 1
Why don't you add the function to the class node.
+ 1
Because I get confused when Value gets changed and when it doesn't... That's Why I did it by this method but here also mutability failed as per my knowledge. :(
+ 1
Thank you so much for your help. :)