Are integers in Python passed by value or reference?

前端 未结 4 919
感情败类
感情败类 2021-02-10 17:02

I wrote the following code to check if integers are passed by value or reference.

foo = 1

def f(bar):
    print id(foo) == id(bar)
    bar += 1
    print foo, b         


        
4条回答
  •  孤街浪徒
    2021-02-10 17:29

    In Python 2, the current implementation keeps an array of integer objects for all integers between -5 and 256. So if you assign a variable as var1 = 1 and some other variable as var2 = 1, they are both pointing to the same object.

    Python "variables" are labels that point to objects, rather than containers that can be filled with data, and thus on reassignment, your label is pointing to a new object (rather than the original object containing the new data). See Stack Overflow question Python identity: Multiple personality disorder, need code shrink.

    Coming to your code, I have introduced a couple more print statements, which will display that the variables are being passed by value

    foo = 1
    def f(bar):
        print id(foo) == id(bar)
        print id(1), id(foo), id(bar) #All three are same
        print foo, bar 
        bar += 1
        print id(bar), id(2)
        print foo, bar
    
    f(foo)
    

提交回复
热议问题