Tuesday, May 10, 2011

[python] Parameters: pass by value or ref?

C is pass-by-value.
Java is pass-by-value.
Python passes references-to-objects by value (like Java), and everything in Python is an object.

Some objects, like strings, tuples, and numbers, are immutable. Altering them inside a function/method will create a new instance and the original instance outside the function/method is not changed.

Other objects, like lists and dictionaries are mutable, which means you can change the object in-place. Therefore, altering an object inside a function/method will also change the original object outside. Assigning a separate object (e.g. creating a new instance) to the input parameter will also not change the original instance.


   def  no_change0(val)
          val *= 2   #original val is not changed.
         
    def  no_change1(inst)
          inst = {}
          inst['anything'] = 'something'  #original inst is not changed!!!


   def  change1(inst)
          inst['anything'] = 'something'  #original inst is changed this time.

No comments: