Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6911476
  • 博文数量: 3857
  • 博客积分: 6409
  • 博客等级: 准将
  • 技术积分: 15948
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-02 16:48
个人简介

迷彩 潜伏 隐蔽 伪装

文章分类

全部博文(3857)

文章存档

2017年(5)

2016年(63)

2015年(927)

2014年(677)

2013年(807)

2012年(1241)

2011年(67)

2010年(7)

2009年(36)

2008年(28)

分类: Python/Ruby

2013-03-21 06:54:32

原文地址:Python局部变量、对象的理解 作者:ymzy

有一段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在同一对象上操作,所以该对象的值改变了。







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