Python 函数的进阶
>>> def my_max(x,y): ... m = x if x>y else y ... >>> my_max(34,88) >>> print(m) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'm' is not defined >>>
报错了!错误是“name 'm' is not defined”。变量m没有被定义。。。为啥?我明明定义了呀!
在这里我们首先回忆一下python代码运行的时候遇到函数是怎么做的。 从python解释器开始执行之后,就在内存中开辟了一个空间 每当遇到一个变量的时候,就把变量名和值之间的对应关系记录下来。 但是当遇到函数定义的时候解释器只是象征性的将函数名读入内存,表示知道这个函数的存在了,至于函数内部的变量和逻辑解释器根本不关心。 等执行到函数调用的时候,python解释器会再开辟一块内存来存储这个函数里的内容,这个时候,才关注函数里面有哪些变量,而函数中的变量会存储在新开辟出来的内存中。函数中的变量只能在函数的内部使用,并且会随着函数执行完毕,这块内存中的所有内容也会被清空。
我们给这个“存放名字与值的关系”的空间起了一个名字——叫做命名空间
代码在运行伊始,创建的存储“变量名与值的关系”的空间叫做全局命名空间,在函数的运行中开辟的临时的空间叫做局部命名空间
命名空间和作用域
命名空间的本质:存放名字与值的绑定关系
>>> import this The Zen of Python, by Tim Peters 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! python之禅
在python之禅中提到过:命名空间是一种绝妙的理念,让我们尽情的使用发挥吧!
命名空间一共分为三种:
内置命名空间
全局命名空间
局部命名空间
*内置命名空间中存放了python解释器为我们提供的名字:input,print,str,list,tuple...它们都是我们熟悉的,拿过来就可以用的方法。
三种命名空间之间的加载与取值顺序:
加载顺序:内置命名空间(程序运行前加载)->全局命名空间(程序运行中:从上到下加载)->局部命名空间(程序运行中:调用时才加载)
取值:
在局部调用:局部命名空间->全局命名空间->内置命名空间
a = 23 def function_my(x): x = 55 print(x) function_my(a)
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 55 Process finished with exit code 0
在全局调用:全局命名空间->内置命名空间
a = 23 def function_my(x): print(x) function_my(58) print(a)
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 58 23 Process finished with exit code 0
print(max)
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py <built-in function max> Process finished with exit code 0
作用域
作用域就是作用范围,按照生效范围可以分为全局作用域和局部作用域。
全局作用域:包含内置名称空间、全局名称空间,在整个文件的任意位置都能被引用、全局有效
局部作用域:局部名称空间,只能在局部范围内生效
globals和locals方法
在全局调用globals和locals
print(globals()) print(locals())
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py {'__name__': '__main__', '__doc__': '\na = 23\n\n\ndef function_my(x):\n x = 55\n print(x)\n\n\nfunction_my(a)\n\n\na = 23\n\n\ndef function_my(x):\n print(x)\n\n\nfunction_my(58)\nprint(a)\n\n\nprint(max)\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001B8C0C31CF8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/YuchuanProjectData/PythonProject/yuchuandemo001.py', '__cached__': None} {'__name__': '__main__', '__doc__': '\na = 23\n\n\ndef function_my(x):\n x = 55\n print(x)\n\n\nfunction_my(a)\n\n\na = 23\n\n\ndef function_my(x):\n print(x)\n\n\nfunction_my(58)\nprint(a)\n\n\nprint(max)\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001B8C0C31CF8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/YuchuanProjectData/PythonProject/yuchuandemo001.py', '__cached__': None} Process finished with exit code 0
在局部调用globals和locals
def function_my(): a = 10 b = 100 print(globals()) print(locals()) function_my()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py {'__name__': '__main__', '__doc__': '\na = 23\n\n\ndef function_my(x):\n x = 55\n print(x)\n\n\nfunction_my(a)\n\n\na = 23\n\n\ndef function_my(x):\n print(x)\n\n\nfunction_my(58)\nprint(a)\n\n\nprint(max)\n\n\nprint(globals())\nprint(locals())\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000252AD391CF8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/YuchuanProjectData/PythonProject/yuchuandemo001.py', '__cached__': None, 'function_my': <function function_my at 0x00000252AD3CC1E0>} {'a': 10, 'b': 100} Process finished with exit code 0
global关键字
a = 20 def function_my(): global a a = 3000 print(a) print(a) function_my() print(a)
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 20 3000 3000 Process finished with exit code 0
函数的嵌套和作用域链
函数的嵌套调用
def my_max(a, b): return a if a > b else b def my_maxs(a, b, c, d): res1 = my_max(a, b) res2 = my_max(res1, c) res3 = my_max(res2, d) return res3 print(my_maxs(32, 65, 2, 26))
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 65 Process finished with exit code 0
函数的嵌套定义
def function1(): print("in function1") def function2(): print("in function2") function2() function1()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py in function1 in function2 Process finished with exit code 0
函数的作用域链
def function1(): a = 66 def function2(): def function3(): print(a) function3() function2() function1()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 66 Process finished with exit code 0
nonlocal关键字
# 1.外部必须有这个变量 # 2.在内部函数声明nonlocal变量之前不能再出现同名变量 # 3.内部修改这个变量如果想在外部有这个变量的第一层函数中生效
a = 60 def function1(): a = 88 def function2(): nonlocal a a = 99 print(a) function2() print("in function1") function1()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 99 in function1 Process finished with exit code 0
函数名的本质
函数名本质上就是函数的内存地址
1.可以被引用
a = 60 def function1(): a = 88 def function2(): nonlocal a a = 99 print(a) function2() print("in function1") print(function1)
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py <function function1 at 0x0000023FF5B8C1E0> Process finished with exit code 0
2.可以被当作容器类型的元素
def function1(): print("int function1") def function2(): print("in function2") def function3(): print("in function3") lis = [function1, function2, function3] disc = {'fun1': function1, 'fun2': function2, 'fun3': function3} lis[1]() disc['fun1']()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py in function2 int function1 Process finished with exit code 0
3.可以当作函数的参数和返回值
*不明白?那就记住一句话,就当普通变量用
第一类对象(first-class object)指 1.可在运行期创建 2.可用作函数参数或返回值 3.可存入变量的实体。
闭包
def function1(): name = "段于传" def inner(): print(name) inner() function1()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 段于传 Process finished with exit code 0
闭包函数:
内部函数包含对外部作用域而非全剧作用域名字的引用,该内部函数称为闭包函数
#函数内部定义的函数称为内部函数
由于有了作用域的关系,我们就不能拿到函数内部的变量和函数了。如果我们就是想拿怎么办呢?返回呀!
我们都知道函数内的变量我们要想在函数外部用,可以直接返回这个变量,那么如果我们想在函数外部调用函数内部的函数呢?
是不是直接就把这个函数的名字返回就好了?
这才是闭包函数最常用的用法
def function1(): name = "段于传" def inner(): print(name) return inner func = function1() func()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 段于传 Process finished with exit code 0
判断闭包函数的方法__closure__
#输出的__closure__有cell元素 :是闭包函数 def function1(): name = "段于传" def inner(): print(name) print(inner.__closure__) return inner func = function1() func()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py (<cell at 0x000001D1A811EA08: str object at 0x000001D1A80FBE70>,) 段于传 Process finished with exit code 0
#输出的__closure__为None :不是闭包函数 name = "段于传" def function1(): # name = "段于传" def inner(): print(name) print(inner.__closure__) return inner func = function1() func()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py None 段于传 Process finished with exit code 0
闭包的嵌套
def wrapper(): name = "段于传" def function(): sex = "male" def inner(): print(sex) print(name) return inner return function fuc = wrapper() fuc1 = fuc() fuc1()
结果:
D:\YuchuanProjectData\PythonProject\venv\Scripts\python.exe D:/YuchuanProjectData/PythonProject/yuchuandemo001.py 段于传 male Process finished with exit code 0
#闭包函数获取网络应用 from urllib.request import urlopen def get_url(): url = "http://www.xiaohua100.cn/index.html" def get(): return urlopen(url).read() return get data = get_url() print(data())
本章小结
命名空间:
一共有三种命名空间从大范围到小范围的顺序:内置命名空间、全局命名空间、局部命名空间
作用域(包括函数的作用域链):
小范围的可以用大范围的 但是大范围的不能用小范围的 范围从大到小(图)
在小范围内,如果要用一个变量,是当前这个小范围有的,就用自己的 如果在小范围内没有,就用上一级的,上一级没有就用上上一级的,以此类推。 如果都没有,报错
函数的嵌套:
嵌套调用
嵌套定义:定义在内部的函数无法直接在全局被调用
函数名的本质:
就是一个变量,保存了函数所在的内存地址
闭包:
内部函数包含对外部作用域而非全剧作用域名字的引用,该内部函数称为闭包函数
- 点赞
- 收藏
- 关注作者
评论(0)