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)
2
  • Possible duplicate of How do I pass a variable by reference? Commented Dec 9, 2017 at 1: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 to see visualization which shows references. Commented Dec 9, 2017 at 2:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is this mechanism like Java?
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.