python废话三:变量:局部变量和全局变量
2016-01-25 09:45
721 查看
下面看代码:
难道这个方法把全局变量改变了?我们再次做个试验:
这个时候打印出来的是test_python python 2.7,也就是说现在这个改变的只是方法内部的数据,我们可以改变全局变量的值呢:
看方法:
看出来在test3()中全局变量已经发生了改变。
str = "python 2.7" //全局变量 def test1(): str = "test_python" //局部变量 print(str) if __name__ == '__main__': test1()这个时候打印出来的是test_python
难道这个方法把全局变量改变了?我们再次做个试验:
str = "python 2.7" def test1(): str = "test_python" print(str) def test2(): print(str) if __name__ == '__main__': test1() test2()
这个时候打印出来的是test_python python 2.7,也就是说现在这个改变的只是方法内部的数据,我们可以改变全局变量的值呢:
看方法:
str = "python 2.7" def test1(): str = "test_python" print(str) def test3(): global str str = "test_python_2" print(str) def test2(): print(str) if __name__ == '__main__': test1() test3() test2()出来的结果是:test_python test_python_2 test_python_2
看出来在test3()中全局变量已经发生了改变。
相关文章推荐
- python --闭包学习
- 使SourceInsight支持Python语言的方法
- python废话二:学习python2还是python3
- 21行Python代码实现拼写检查器
- Python--(高阶)函数
- Python Unit Testing
- Python Unit Testing
- 44. Wildcard Matching leetcode Python 2016 new season
- 43. Multiply Strings leetcode python 2016 new season
- Python常用函数
- Python如何进行cross validation training
- Python/Keras如何将给定的数据集打乱
- Python-装饰器以及对带有参数的装饰器的理解
- Python 删除列表中的重复数据
- 21行Python代码实现拼写检查器
- 基于Python Shell获取hostname和fqdn释疑
- 谈谈Python进行验证码识别的一些想法
- Python网站验证码识别
- 详解Python验证码识别
- Python开发如何在ubuntu 15.10 上配置vim