0

I have read, multiple times, that python passes arguments by value. However, I was testing the following simple code, and it looks like the class c objects are passed by reference (a modification inside the function modifies the object). Could someone please explain why so?

Code:

class c:
    def __init__(self,i):
        self.i=i

def incr_obj(obj):
    obj.i+=1

oo=c(1)
incr_obj(oo)
print(oo.i)

it prints 2.

  • 1
    *I have read, multiple times, that python passes arguments by value* - where have you read that? – Jon Clements Apr 27 '22 at 10:29
  • For example: https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ – user18170958 Apr 27 '22 at 10:30
  • 3
    Okay... ignore that... read this: https://nedbatchelder.com/text/names.html – Jon Clements Apr 27 '22 at 10:32
  • Whatever Python is, it's definitely not pass by value. Any function can mutate its arguments (if they are mutable). – Jussi Nurminen Apr 27 '22 at 10:35
  • OK, thank you! @JonClements So if I understood well, any user defined object is mutable in python, and thus is passed by reference, right? – user18170958 Apr 27 '22 at 10:40
  • Thank you, @JussiNurminen. I didn't know that user defined objects are mutable before – user18170958 Apr 27 '22 at 10:41
  • Regardless of whether an object is mutable or not, it is "passed by reference" (that's not exactly correct, but close enough). The function gets a reference to the object, and if it's mutable, the function can mutate it. – Jussi Nurminen Apr 27 '22 at 10:43
  • And yes, most user defined types are mutable. For example, any class you define or a class instance is going to be mutable. – Jussi Nurminen Apr 27 '22 at 10:45
  • Oh, OK. So that's because values are not repeated, and x=a is just referring to the value of a using x..., right? But it still holds that any object that I define must be mutable, right? – user18170958 Apr 27 '22 at 10:48
  • 1
    The Ned Batchelder article linked above is really well written and clear. If you take the time to read it carefully, you will perfectly understand values and names (references) in Python :) – Jussi Nurminen Apr 27 '22 at 10:50
  • Ok, I will make sure I do :) – user18170958 Apr 27 '22 at 10:52

0 Answers0