成都创新互联网站制作重庆分公司

python函数嵌套报错 python函数嵌套如何执行

关于python 函数嵌套

因为最后的那句return nested。

创新互联公司是一家专注于成都网站设计、做网站与策划设计,山海关网站建设哪家好?创新互联公司做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:山海关等地区。山海关做网站价格咨询:18980820575

tester()()会自动调用它的返回值,而此时的返回值为nested,即def nested()这个函数,所以自然而然执行到了里面的print语句。

你可以试试把最后那就return nested改成其他的如return nestedxxx,再tester()()时就会报错了。

另外,在python里对于方法ester和nested是没有tester().nested()这种用法的,所以这样输入肯定报错的,如果ester和nested是类(class)的话才有这种写法。

希望对你有所帮助~~

python函数不使用nonlocal关键字报错原因怎么写

global

python 函数嵌套和nonlocal关键字

只待风起

原创

关注

3点赞·7531人阅读

python函数可以嵌套使用,使用也比较简单,举个栗子:

def outer():

print("outer")

def inner():

print("inner")

inner()

outer()

## 运行结果:

outer

inner

复制

nonlocal关键字:

与global关键字有点相似,可以对比着理解。nonlocal关键字只能作用域局部变量,且始终找离当前最近的上层局部作用域中的变量。看栗子:

a = 1

def outer():

nonlocal a

a = 2

outer()

print(a)

复制

结果:报错  SyntaxError: no binding for nonlocal 'a' found,

原因分析:nonlocal关键字是能作用域局部变量,当使用nonlocal声明变量 a 时,就会往上最近一层局部作用域寻找局部变量 a ,结果没找着,报错。

a = 1

def outer():

global a

a = 2

def inner():

nonlocal a

a = 3

inner()

print(a)

outer()

print(a)

复制

结果:报错  SyntaxError: no binding for nonlocal 'a' found,

原因分析:当使用nonlocal声明变量 a 时,就会往上最近一层局部作用域寻找局部变量 a ,此时外层局部作用域虽然能找到变量a,但是这找到的 这个a 已经被global声明为全局变量了,所以报错。

a = 1

def outer():

a = 2

def inner():

nonlocal a

a = 3

def inner2():

print(a)

inner2()

print(a)

inner()

print(a)

outer()

print(a)

## 运行结果:

3

3

3

1

python自定义函数传嵌套字典出错

应该是用大括号的 # create a mapping of state to abbreviationstates = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI'}# create a basic set of states and some cities in themcities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}


本文标题:python函数嵌套报错 python函数嵌套如何执行
地址分享:http://cxhlcq.com/article/doisijj.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部