중첩 함수 범위에서 UnboundLocalError 해결
Python 인터프리터는 중첩 함수 내의 바인딩되지 않은 지역 변수에 액세스할 때 UnboundLocalError를 발견합니다. 이 문제는 중첩 함수가 외부 함수 내에 선언된 변수를 수정하려고 할 때 발생합니다.
예:
다음 코드를 고려하세요.
<code class="python">def outer(): ctr = 0 def inner(): ctr += 1 inner()</code>
이 코드를 실행하면 인터프리터가 다음 오류를 생성합니다.
Traceback (most recent call last): File "foo.py", line 9, in <module> outer() File "foo.py", line 7, in outer inner() File "foo.py", line 5, in inner ctr += 1 UnboundLocalError: local variable 'ctr' referenced before assignment</module>
원인:
중첩된 범위가 있음에도 불구하고 내부 함수는 'ctr'에 액세스할 수 없습니다. ' 변수는 외부 함수에 정의되어 있으므로 직접 변수입니다. 이로 인해 바인딩되지 않은 변수가 발생하고 UnboundLocalError가 발생합니다.
해결책:
Python 3은 중첩된 범위에서 변수 리바인딩을 활성화하는 'nonlocal' 문을 제공합니다. '비로컬'을 포함하도록 코드를 수정하면 문제가 해결됩니다.
<code class="python">def outer(): ctr = 0 def inner(): nonlocal ctr ctr += 1 inner()</code>
Python 2 사용자의 경우 대체 접근 방식이 필요합니다.
-
기본 이름 제거:
기본 ctr 변수를 제거하고 데이터 구조 내에 또는 속성으로 배치합니다. 예를 들어 ctr = [0]. -
변수 재할당:
barename 리바인딩을 사용하는 대신 내부 함수 내에서 ctr 변수를 재할당합니다. ctr = ctr 1.
위 내용은 중첩된 함수 범위에서 바인딩되지 않은 지역 변수 오류를 처리하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경