Chinaunix首页 | 论坛 | 博客
  • 博客访问: 176188
  • 博文数量: 27
  • 博客积分: 1649
  • 博客等级: 上尉
  • 技术积分: 274
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-22 22:45
文章分类

全部博文(27)

文章存档

2013年(3)

2012年(5)

2011年(2)

2010年(17)

分类: Python/Ruby

2013-03-20 01:41:23

有一段python代码

test.py

  1. # -*- coding: gbk -*-

  2. def f(dictVar):
  3.     print "赋值前 dictVar:",dictVar
  4.     dictVar = {"key2":"value2"}
  5.     print "赋值后 dictVar:",dictVar

  6. if __name__ == "__main__":
  7.     dictVar = {"key1":"value1"}
  8.     print "调用函数前 dictVar:", dictVar
  9.     
  10.     print "调用函数"
  11.     
  12.     f(dictVar)
  13.     
  14.     print "调用函数后 dictVar:", dictVar

运行结果如下:



解释:

main模块里面的变量dictVarfun函数里面的变量dictVar是两个不同的变量,由于他们的名字相同,所以很容易混淆,认为他们是同一变量。

  1. dictVar = {"key1":"value1"} //将dict指向{“key1”:”value1”}对象


其实python里面的一个变量就是PyObject *的指针变量,可以指向任意类型的对象。


  1. dictVar = {"key2":"value2"}

dictVar赋值,使其指向了{“key2”:”value2”}对象,__main__模块的dictVar变量,其指向的对象则不变。


    退出fun函数后,局部变量dictVar被释放,恢复主模块的作用域,dictVar仍然指向{“key1”:”value1”}


    关于python对象的理解

test2.py

  1. # -*- coding: gbk -*-

  2. def f(dictVar):
  3.     print "赋值前 dictVar:",dictVar
  4.     dictVar.update({"key2":"value2"})
  5.     print "赋值后 dictVar:",dictVar

  6. if __name__ == "__main__":
  7.     dictVar = {"key1":"value1"}
  8.     print "调用函数前 dictVar:", dictVar
  9.     
  10.     print "调用函数"
  11.     
  12.     f(dictVar)
  13.     
  14.     print "调用函数后 dictVar:", dictVar
    以上代码的执行结果是:

    dictVar.update({"key2":"value2"})是在{“key1”:”value1”}dict对象上操作的,dictVar在同一对象上操作,所以该对象的值改变了。







阅读(4013) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~