Discuss / Python / 交作业顺便解疑

### 交作业顺便解疑

Topic source

#### 烈可烈

#1 Created at ... [Delete] [Delete and Lock User]
def createCounter():
f = [0]
print('闭包外--')
def counter():
print('闭包内--')
f[0] = f[0] + 1
return f[0]
return counter
# 测试
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA())


def counter():
print('闭包中--')
f[0] = f[0] + 1
return f


print是等内容全部执行完，再输出的。

#### test_number

#2 Created at ... [Delete] [Delete and Lock User]

#### 爱喝白开shui

#3 Created at ... [Delete] [Delete and Lock User]

def createCounter():
f = 0
print('闭包外--')
def counter():
print('闭包内--')
f = f + 1
return f
return counter


闭包外--

Traceback (most recent call last):
File "t.py", line 20, in <module>
print(counterA(), counterA(), counterA(), counterA(), counterA())
File "t.py", line 6, in counter
f = f + 1
UnboundLocalError: local variable 'f' referenced before assignment


#### 爱喝白开shui

#4 Created at ... [Delete] [Delete and Lock User]

def createCounter():
f = 0
print('闭包外--')

def counter():
print('闭包内--')
nonlocal f
f += 1
return f
return counter


#### john小师弟

#5 Created at ... [Delete] [Delete and Lock User]

#### 初见-好久不见

#6 Created at ... [Delete] [Delete and Lock User]

##内层函数能访问外层函数的变量，但不能修改它的指向

def createCounter():
count = [0]
def counter():
count[0] += 1
return count[0]
return counter


##这种情况可行是因为count指向的是一个列表的实例对象，实质上，列表的实例对象的地址一直没变，只是其内容的指向改变了而已

###而nonlocal关键字用来在函数或其他作用域中修改外层(非全局)变量

def createCounter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter


###global关键字则是用于修改全局变量

#python引用变量的顺序： 当前作用域局部变量->外层作用域变量->当前模块中的全局变量->python内置变量

#### 用户6150886020

#7 Created at ... [Delete] [Delete and Lock User]

#### 背着阳光奔跑的猴子

#8 Created at ... [Delete] [Delete and Lock User]

#### 墨染苍瞳

#9 Created at ... [Delete] [Delete and Lock User]

#### upbeat_peach

#10 Created at ... [Delete] [Delete and Lock User]

<function createCounter.<locals>.counter at 0x0000000002895730> <function createCounter.<locals>.counter at 0x00000000028957B8> <function createCounter.<locals>.counter at 0x0000000002895840> <function createCounter.<locals>.counter at 0x00000000028958C8> <function createCounter.<locals>.counter at 0x0000000002895950>

• 1
• 2