python local函数_python知识点@函数嵌套,内置函数nonlocal和global

本文主要内容:

一、函数的嵌套

案例1

代码的执行顺序是按从上到下执行,以下给大家列出代码的执行顺序,代码先加载函数名.函数真正调用的时候加载函数里的代码

def test1(): #1

print("test1方法----") #6

def test2(): #2

print("test2方法") #4

test2()#3

test1()#5

print("test1方法")#7

输出:

test2方法

test1方法----

test1方法

案例2

def test1(): #1

print("test1方法") #4

def test2():#5

print("test2方法") #8

print("****1") #6

test2() #7

print("****2") #9

print("***3") #2

test1()#3

print("***4") #10

#输出:

***3

test1方法

****1

test2方法

****2

***4

二、 内置函数gloabal、nonlocal

1、注意:关键字nonlocal:是python3.X中出现的,所以在python2.x中无法直接使用

2、区别:

(1)global关键字用来在函数或其它局部作用域中使用全局变量。但是如果不使用全局变量也可以不适用global关键字声明。

(2)nonlocal关键字用来在函数或其它作用域中使用外层(非全局)变量

3.具体例子:

函数gloabal的使用

a = 10

def test1():

global a

print(a)

a = 100

print(a)

test1()

print(a)

输出:

10

10

100

对于可变数据类型可以直接进⾏访问

lst = ["python", "java", "C++"]

def func():

lst.append("C")

print(lst)

func()

print(lst)

函数nonlocal的使用

带有nonlocal a

a = 100

def test1():

a = 200

def test2():

nonlocal a

a = 300

print(a)

test2()

print(a)

test1()

#输出:

300

300

没有nonlocal a

a = 100

def test1():

a = 200

def test2():

a = 300

print(a)

test2()

print(a)

test1()

#输出:

300

200

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值