0

In the code segment below,

class Test:
    def __init__(self, val):
        self.val = val


def insert(x):
    if x == None:
        x = Test(10)

obj =  None
insert(obj)
print(obj.val)

I was expecting the output of the print statement to be 10 but am getting AttributeError: 'NoneType' object has no attribute 'val'. This is because the obj is not being modified by the function and is still None after the call to the insert function. As far as I knew, all objects are passed by reference in python. How can I get around this and modify the object without returning its new value?

3
  • 3
    Things don't work like that for primitive types in python. You may return x from insert function. Commented Jun 10, 2017 at 5:34
  • 1
    If you really want to mutate the parameter in insert, pass a one-item list: def insert(x): if x[0] == None: x[0] = Test(10); obj=[None];insert(obj);print(obj[0].val) Commented Jun 10, 2017 at 5:43
  • @AhsanulHaque could you please elaborate? I was thinking that I was passing a reference to a NoneType object and that reference was being assigned a reference to a Test Object. Then why isn't the change reflected in the original object? Commented Jun 10, 2017 at 5:50

1 Answer 1

1

first, you must return the variable from the function insert.

Second, you have to assign the line insert(obj) to a Variable.

Val is still inside Test class. you must Print it from inside the class. also , obj.val is Not exists.

class Test:
    def __init__(self, val):
        self.val = val
        print(val)



def insert(x):
    if x == None:
        x = Test(10)
    return(x)

obj =  None
Var_Ref=insert(obj)
print(Var_Ref)
Sign up to request clarification or add additional context in comments.

2 Comments

You confuse global and static variables.
i used it to simpify the idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.