class x:
def __init__(self):
self.y=None
self.sillyFunc(self.y)
def sillyFunc(self,argument):
if argument is None:
argument='my_name_as_argument'
self.printy()
def printy(self):
print self.y
According to me the above code should print >my_name_as_argument,where am i going wrong?
In Python everything is an object and variables contain references to objects. When you make a function call it makes copies of the references. Some people including Guido van Rossum call this “Call by object reference”. Important note from Wikipedia:
The code as you posted it prints nothing at all. I think you mean to add this extra line to your program:
This then results in the output:
None. This is not surprising because you are printing the value ofself.ybut the only value you ever assign toself.yisNone.In Python, strings are immutable. Reassigning the value of
argumentonly overwrites the local copy of the reference. It does not modify the original string.As you asked in a comment, if you use a mutable object and you reassign the reference, again this doesn’t do what you want – the original object is not affected. If you want to mutate a mutable object you can call a method that mutates it. Simply reassigning a reference does not change the original object.
If you want
self.yto point to a new object then you have to assign the object reference directly toself.y.