다른 반복자의 길이를 계산하면서 반복하는 iterator를 만들고 싶습니다. 가 여기에 내가 무엇을 달성하고자하는 작업 예입니다 : 내가 전역 변수를 사용하고자하는 경우에는중첩 된 iterator가 중첩 된 메서드에서 변수에 액세스합니다.
from random import random
def randleniter(p):
while random() < p:
yield 7
count = 0
def do():
def countiter(piter):
global count
for i in piter:
count += 1
yield i
list(countiter(randiter(0.99))) #simulator for a different method consuming the iterator
return count
>>> do()
81
,이처럼 내장 된 적이없는 것입니다.
def make_adder(x):
def add(y):
return x + y
return add
내가이 일을 할 수있을 것입니다 :
def do():
count = 0
def countiter(piter):
for i in piter:
count += 1
yield i
list(countiter(randiter(0.99)))
return count
을하지만 이것은 UnboundLocalError: local variable 'count' referenced before assignment
결과 나는 중첩 된 방법으로이 작업을 수행 할 수 있기 때문에 상상. countiter
안에있는 print locals()
의 경우 - count
이 포함되지 않습니다. countiter
에 count
님께 어떻게 연락 할 수 있습니까?
이유는 단순한 클래스를 해결할 만드는 물론 간단한 클래스 –
@PadraicCunningham을하지 내 질문 방법 "이 아니었다 이유입니다. 이 일을하라 "- 과정 중에 배우고 싶다. – Korem
분명히 발전기는 우리가 될 수 없다. "closure-fashion"에서 편집. –