Are integers in Python passed by value or reference?

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

    The following happens:

    print id(foo) == id(bar)
    

    The identity is the same. print foo is bar would have yielded the same, BTW.

    bar += 1
    

    This is translated to:

    bar = bar.__iadd__(1)
    

    And only if this does not work or does not exist, it calls:

    bar = bar.__add__(1)
    

    (I omit the case that bar = 1.__radd__(bar) could as well be called.)

    As bar refers to a number, which is immutable, a different object is returned instead, so that bar refers to 2 now, leaving foo untouched.

    If you do any of

    print id(foo) == id(bar)
    print foo is bar
    

    now, you see that they now point to different objects.

提交回复
热议问题