首页 / PYTHON / Python学习之函数进阶
Python学习之函数进阶
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python学习之函数进阶,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2236字,纯文字阅读大概需要4分钟。
内容图文
![Python学习之函数进阶](/upload/InfoBanner/zyjiaocheng/1084/dded7dd7476842d1a5ebca39127b986f.jpg)
函数的命名空间
著名的python之禅
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren‘t special enough to break the rules.Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you‘re Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it‘s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let‘s do more of those!
命名空间的分类:(1)全局命名空间(2)局部命名空间(3)内置命名空间
三种命名空间的加载与取值顺序
加载顺序:内置命名空间(程序运行前加载)->全局命名空间(程序运行中:从上到下加载)->局部命名空间(程序运行中:调用时才加载)
取值时分为:局部调用和全局调用
局部调用:局部命名空间->全局命名空间->内置命名空间
x = 1 def f(x): print(x) print(10)
全局调用:全局命名空间->内置命名空间
x = 1 def f(x): print(x) f(10) print(x)
函数的作用域:按照生效范围可以分为全局作用域和局部作用域。
通过global和local可以更改函数的作用域。
函数的嵌套与作用域:
函数的嵌套
def f1(): def f2(): def f3(): print("in f3") print("in f2") f3() print("in f1") f2() f1()
函数的作用域
def f1(): a=1 def f2(): a=2 def f3(): a=3 print("a in f3:",a) print("a in f2:",a) f3() print("a in f1:",a) f2() f1() def f1(): a = 1 def f2(): a = 2 print(‘a in f2 : ‘, a) f2() print(‘a in f1 : ‘,a) f1()
nonlocal关键字(不是本地的)
使用要求:
1.外部必须有这个变量
2.在内部函数声明nonlocal变量之前不能再出现同名变量
3.内部修改这个变量如果想在外部有这个变量的第一层函数中生效
def f1(): a = 1 def f2(): nonlocal a a = 2 f2() print(‘a in f1 : ‘,a) f1()
函数名的本质是函数的内存地址:它可以被引用、被当作容器类型的元素、当作函数的参数和返回值。
闭包函数:
常用方式
def func(): name = ‘eva‘def inner(): print(name) return inner f = func() f()
用途:我们在外部函数调用内部函数时
闭包函数的嵌套:
def wrapper(): money = 1000 def func(): name = ‘eva‘def inner(): print(name,money) return inner return func f = wrapper() i=f() print(i) i()
嵌套了几个就要加括号执行几个
闭包函数的应用:
from urllib.request import urlopen def index(): url = "http://www.xiaohua100.cn/index.html"def get(): return urlopen(url).read() return get xiaohua = index() content = xiaohua() print(content)
原文:http://www.cnblogs.com/1a2a/p/7258214.html
内容总结
以上是互联网集市为您收集整理的Python学习之函数进阶全部内容,希望文章能够帮你解决Python学习之函数进阶所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。