函数对象,名称空间及查找,作用域

函数是第一类对象:函数名指向的值可以被当做数据去使用 1.被引用 def index (): print('hello') f = index f() 2,可以当参数 def bar(a): print(a) bar(index)#输出结果为函数地址 3,可以当作函数的返回值 def outter(): x =1 def inner(): print('inner') return inner #把内部函数当做外部的返回值返回出来 f =outter() f() 4,可以当做容器类型的元素 l=[age,func,func()] 调用案例: def login (): print('login') def shoping(): print('shoping') def pay (): print('pay') def other(): print('other')

msg = { "1":login, "2":shoping, "3":pay, '4':other } while True: print(""" 1.登陆 2.购物 3.付款 4.其他 5.退出 """) choice = input("请输入序号") if choice =='5': break elif choice not in msg: print('请输入正确的数字') else:msgchoice

 

函数的嵌套调用

函数嵌套调用例子:比较四个数的最大值

def index4(x,y,z,q): res1 = index(x,y) res2 = index(res1,z) res3 = index(res2,q) print(res3) index4(1,2,34,5)

函数的嵌套定义:函数内定义新得的函数,外部函数无法访问内部函数的值,只能访问同级别或上一层级别的值,如果上一层包含访问对象但在内层调用前未赋值,则发生报错

def outter (): x = 1 def inner(): print(x) inner(x) def main (choice): def shopping(): print('shoping') def pay(): print("pay") def other(): print('other') if choice == 1: shopping() elif choice == 2: pay() elif choice ==3: other() else: print("输入有误")

名称空间

名称空间三大类:

内置名称空间:python解释器自带的名字(解释器打开生效,关闭失效)

 

全局名称空间:文件级别的名字,for,while ,if 内部定义执行后的名字也存放于全局变量(py文件启动生效,关闭失效)

 

局部名称空间:在函数内定义的名字(函数调用生效,停止失效)

 

名称查找顺序

根据查找位置依次向外查找

局部——>全局——>内置

函数内变量在定义阶段就已经定死了,不会改变查找的位置(局部,全局,内置)

除了可变参数例如

 

作用域

global

x = 1 def index(): global x #声明全局变量 x =2 print(x) index() print(x)

nonlocal

def index(): x = 1 def func(): nonlocal x#声明局部变量 x =2 func() print(x) index()

 

可变类型在局部修改外部的值

l = [2] def index(a): l.append(a) print(l)

print(index(122)) print(l) #输出都是[1,122]

l = 1 def index(a): l=a print(l)

print(index(122)) #122 print(l) #1

posted @ 2019-11-14 21:33  D山仙  阅读(104)  评论(0编辑  收藏  举报