-3

I have the following piece of code:

class test:

def __init__(self):
    self.variable = 'Old'
    self.change(self.variable)

def change(self, var):
    var = 'New'


obj = test()
print(obj.variable)

The output is Old but I don't understand - the method change gets a REFERENCE to the class variable variable then why doesn't self.variable change to New if I assigned a new string to the pointer inside the class ?

I know the string itself is immutable but doesn't it change the value of the pointer represented by self.variable ?

Wouldn't it be the same as: *var = 'New' in C ?

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
Caffeine
  • 113
  • 1
  • 1
  • 7
  • 1
    `var` is a local variable inside the function and it has nothing to do with `self.variable` even their names are not the same which even if they were you should've used `self` reference to access to it. – Mazdak Jun 27 '18 at 06:44
  • [This](https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/) might be helpful – roganjosh Jun 27 '18 at 06:46
  • But why doesn't "var" evaluate to the pointer of "variable" ? – Caffeine Jun 27 '18 at 06:48
  • You should read the link I gave. It isn't a pointer. – roganjosh Jun 27 '18 at 06:49
  • Thanks, it's more clear now. – Caffeine Jun 27 '18 at 07:02
  • "the method `change` gets a REFERENCE to the class variable `variable`" - no, it gets a reference to a string object. `variable` also has a reference to that string object. Rebinding one reference doesn't affect the other. Python references only refer to objects, not variables. – user2357112 Jun 27 '18 at 07:05

2 Answers2

0

@roganjosh already pointed you to the right blog post. It comes down to Python does not pass the variables by reference or by value but by assignment. You can reference these posts for further elaboration:

  1. Python functions call by reference
  2. How do I pass a variable by reference?
  3. https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
0

As mentioned in the comments by Kasaramvd and the link provided by roganjosh above, var is just a local name which refers to an immutable object. All the change() function can do is create a name var in its local namespace and bind it to a the different immutable object 'New'.

Works when using self.variable instead of var:

def __init__(self):
    self.variable = 'Old'
    self.change()

def change(self):
    self.variable = 'New'
jnd940
  • 21
  • 3