[英]Python - Inner Functions, Closures, and Factory Functions - how to factor out?
[英]closures with two inner functions python
我正在嘗試編寫一個包含兩個內部函數的閉包,但出現以下錯誤
def factory(n=0):
#n=0
def current():
return n
return current
def counter():
n=n+1
return n
return counter
f_current,f_counter = int(input())
print(f_counter())
print(f_current())
我有以下錯誤:
>>4
Traceback (most recent call last):
File "C:/Users/lokesh/Desktop/python/closure3.py",
line 13, in <module>
f_current,f_counter = int(input())
TypeError: 'int' object is not iterable
我的要求是在輸入 4 之后,它應該顯示:
4
5
我是 python 的新手,有人可以幫我嗎...在此先感謝
這看起來更像你想要的:
def factory(n=0):
def current():
return n
def counter():
nonlocal n
n += 1
return n
return current, counter
f_current, f_counter = factory()
print(f_current())
print(f_counter())
print(f_current())
print(f_counter())
輸出:
0
1
1
2
以4
作為輸入:
f_current, f_counter = factory(4)
print(f_current())
print(f_counter())
4
5
factory()
返回兩個內部函數。 您需要使用nonlocal
來遞增n
形成封閉函數。 沒有nonlocal
你將無法修改n
但會得到:
UnboundLocalError: local variable 'n' referenced before assignment
因為n
只是一個局部變量。 nonlocal n
使n
來自封閉函數,可在內部函數內部修改。 在current
中評估n
很好,因為 Python 的作用域規則允許從外部作用域讀取變量,這里是從封閉函數的作用域。
嗨,邁克,我認為非本地人沒有任何意義,我正在提供適用於我的案例的解決方案。
def factory(n):
def current():
return n
def counter():
n=int(current())
n=n+1
return n
return current, counter
n=0
f_current, f_counter = factory((input()))
print(f_current())
print(f_counter())
def factory(n=0):
def current():
return n
def counter():
return n+1
return current, counter
f_current, f_counter = factory(int(input()))
print(f_current())
print(f_counter())
Mike的Nonlocal用法很好,但是我們也可以通過Counter內部函數內部的一個新變量m從封閉作用域訪問n的變量值,遞增后返回。這樣就不需要Nonlocal了。
def factory(n=0):
def current():
return n
def counter():
m=n
m=m+1
return m
return current,counter
f_current,f_counter=factory(int(input()))
print(f_current())
print(f_counter())
`
您可以簡單地使用一個新變量作為內部函數的參數,它等於外部函數的參數並繼續。
def factory(n=0):
def current():
return n
def counter(x=n):
return x+1
return current, counter
f_current,f_counter =factory(int(input()))
print(f_current())
print(f_counter())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.