【问题标题】:python integer argument value is not changing even though id() is same in calling and called functions即使 id() 在调用和被调用函数中相同,python 整数参数值也不会改变
【发布时间】:2015-03-01 11:08:30
【问题描述】:
def func(x):
    print "inside function" ,id(x)
    x = 2
x = 50
print "outside function" ,id(x)
print 'Value of x before function call is', x
func(x)
print 'Value of x after function call is', x

输出:

outside function 6486996
Value of x before function call is 50
inside function 6486996
Value of x after function call is 50

假设id() 给出了对象的内存位置。即使两者都保存在同一个位置,如果在func()中更改了x值,则不会影响到外部。

【问题讨论】:

    标签: python call-by-value


    【解决方案1】:

    如果你想了解更多,我想你需要完全理解基本的python。

    关于你的问题:

    可变对象作为参数

    该函数获得对该对象的引用并可以对其进行变异,但是如果您在方法中重新绑定该引用,则外部范围一无所知,完成后,外部引用仍将指向原始对象。

    不可变对象作为参数

    仍然不能重新绑定外部引用,甚至不能改变这个对象。

    cmets 更新:所以你将 x(Integer immutable) 传递给函数调用,你不能改变这个对象。而你在函数中重新绑定x引用,外部范围一无所知,完成后,外部引用仍然指向原始整数50对象。

    【讨论】:

    • 由于这里发生了重新绑定,因此在这种情况下无需区分可变和不可变。
    • 另外,整数在 Python 中是不可变的,这就是它们可以被实习的原因。
    【解决方案2】:

    赋值通常会更改名称和对象之间的绑定(当然,如果您不这样做,例如x = x)。它不会对对象进行任何更改(无论如何都不会在 ints 上工作,因为它们是不可变的,但只是作为旁注)

    所以在这种情况下,函数内的x 指向50 对象,直到您更改它。然后它指向另一个对象。对象本身不受影响。

    指出一步一步发生的事情:

    • x 外部指向值为 50 的 int 对象
    • 函数调用:x 内部指向同一个对象
    • x 内部改为指向不同的对象,值为 2
    • return:外面x仍然指向50。

    【讨论】:

      【解决方案3】:

      啊,但是函数中的id(x)调用引用了传递给函数的全局x,但是x = 2创建了一个新的局部x。试试这个:

      def func(x):
          print "inside function", id(x)
          x = 2
          print "still inside function", id(x)
      
      x = 50
      print "outside function" , id(x)
      print 'Value of x before function call is', x
      func(x)
      print 'Value of x after function call is', x
      

      典型输出

      outside function 168950596
      Value of x before function call is 50
      inside function 168950596
      still inside function 168951172
      Value of x after function call is 50
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        • 2021-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多