0

I know that python pass object by reference, but why the second output of codes below is 3 other than 10?

class a():
    def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)

b = a(3)
print(b.value)
test(b)
print(b.value)
Jenny
  • 37
  • 1
  • 7
  • Possible duplicate of [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – bunji Dec 09 '17 at 01:57
  • inside `test` you have local variable `b` which first had assigned `a(3)` but later you assign `a(10)` but it doesn't change object assigned to external `b`. Maybe run it on [pythontutor.com](http://pythontutor.com) to see visualization which shows references. – furas Dec 09 '17 at 02:02

2 Answers2

2

Python objects are passed by value, where the value is a reference. The line b = a(3) creates a new object and puts the label b on it. b is not the object, it's just a label which happens to be on the object. When you call test(b), you copy the label b and pass it into the function, making the function's local b (which shadows the global b) also a label on the same object. The two b labels are not tied to each other in any way - they simply happen to both be currently on the same object. So the line b = a(10) inside the function simply creates a new object and places the local b label onto it, leaving the global b exactly as it was.

Curtis Lusmore
  • 1,822
  • 15
  • 16
0
  1. You did not return a value from the function to put into the class. This means the 'b' is irrelevant and does nothing. The only connection is the name 'b'

  2. You need to reassign the value 'b' to be able to call the class.

class a():

def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)
    return b

b = a(3)
print(b.value)

b = test(3)
print(b.value)
johnashu
  • 2,167
  • 4
  • 19
  • 44