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?

banad
  • 491
  • 1
  • 5
  • 15
  • 3
    Things don't work like that for primitive types in python. You may return `x` from `insert` function. – Ahsanul Haque Jun 10 '17 at 05: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)` – DYZ Jun 10 '17 at 05: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? – banad Jun 10 '17 at 05:50

1 Answers1

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)
Mr Sam
  • 981
  • 1
  • 8
  • 12