python 返回值和作用域


# 函数返回值
# return [1, 3, 5] 返回一个列表
# return 1, 3, 5 看似返回一个值,其实是被隐式的封装成一个元组
# x, y, z, = XX() 用来接收返回值

# 函数嵌套 - 引出作用域的概念
def outer():
def inner():
print('inner')
print('outer')
inner()

# 变量在函数外部
x = 100
def show(): # pass
print(x)
show()

# x = 100
# def show(): # fail(local variable 'x' referenced before assignment)
# x += 1
# print(x)
# show()

# 全局作用域(global - 可以在函数外部定义),局部作用域(local - 函数内)
# 注意赋值即定义的概念
x = 100 # 可以在函数外部定义赋值
def foo():
global x # 全局作用域
x += 1
print(x)
foo()

def foo():
global x # 全局作用域
x = 200 # 可以在函数内部定义赋值
x += 1
print(x)
foo()

# global不要使用,可以通过参数来传递*

# 自由变量:没在本地作用域中定义的变量,如:嵌套函数中外层函数的变量对于内层函数来说就是自由变量
# 闭包:在嵌套函数中,内层函数应用了外层函数的自由变量,对于内层函数来说就叫闭包*
def counter():
c = [0]
def inner():
c[0] += 1 # 对外部变量进行改变,Python2只能这么写
return c[0]
return inner

foo = counter()
print(foo())
c = 100
print(foo())

# nonlocal(Python3)

猜你喜欢

转载自www.cnblogs.com/lizitest/p/9553636.html