여러 번 처음 함수를 호출 할 때 간단한 함수를 사용해야 할 필요가있었습니다. 많은 이유가 있지만 일반적으로 처음 실행하면 변수를 다르게 초기화해야합니다. 때로는 함수 나 내부의 문제를 처리 할 수 있지만 때로는 문제가 복잡해질 수 있으며이를 피할 수 있으면 "전역"을 사용하지 않습니다.클래스와 같은 함수 초기화
내 솔루션은 발전기에서 나왔습니다. 프로그램에서 next() 호출을 사용하여 함수의 루프 위에있는 "수율"함수를 사용하여 함수를 "초기화"하거나 함수를 "프라임"할 수 있음을 발견했습니다. 매력처럼 작동합니다.
지금 제 질문은 : 누락 된 수있는 더 나은 방법이 있습니까?
WoNUX - 작동하지만, 비 유용 exammple :
o_PrintList = g_PrintThis() ## Creates func object
o_PrintList.next() ## 'Primes' the func
o_PrintList.send(9) ## Sends argument to the func
o_PrintList.send(10) ## Another argument to the func
def g_PrintThis():
v_PrintList = [] ## Inits the variable. If stnd func call this would happen everytime
print("Initialized")
v_Num = yield ## Waits for first send argument
while True: ## Infinite loop. Could be a for loop, etc.
v_PrintList.append(v_Num) ## Reason v_PrintList needs 'primed'
if not v_PrintList:
print("PrintList is empty:")
else:
print("Printlist: %s") %(v_PrintList)
v_Num = yield ## Waits for next send argument, if ever one comes
감사합니다.
http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function –
명시 적으로 '다음'을 프라임으로 지정하는 경우 그것, 당신은 단지'setup_printing' 함수를 별도로 가지고 처음 설치를 위해 호출 할 수 있습니다. – user2357112