Are integers in Python passed by value or reference?

前端 未结 4 921
感情败类
感情败类 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:13

    There seems to be a lot of confusion around this "issue". Variables names in Python are actually all references to objects. Assignements to variable names aren't actually changing the objects themselves, but setting the reference to a new object. So in your case:

    foo = 1 #
    
    def test(bar):
        # At this point, "bar" points to the same object as foo.
        bar = 2    # We're updating the name "bar" to point an object "int(2)".
        # 'foo' still points to its original object, "int(1)".
        print foo, bar # Therefore we're showing two different things.
    
    test(foo)
    

    The way Python's syntax resembles C and the fact many things are syntactic sugar can be confusing. Remembering that integer objects are acually immutable, and it seems weird that foo += 1 could be a valid statement. In actuality, foo += 1 is actually equivalent to foo = foo + 1, both of which translate to foo = foo.__add__(1), which actually returns a new object, as shown here:

    >>> a = 1
    >>> id (a)
    18613048
    >>> a += 1
    >>> id(a)
    18613024
    >>>
    

提交回复
热议问题