Skip to content Skip to sidebar Skip to footer

Python Object As Argument Of A Function

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

Solution 1:

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.

Solution 2:

  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

deftest(b):
    b = a(10)
    return b

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

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

Post a Comment for "Python Object As Argument Of A Function"