중첩된 함수 범위 및 UnboundLocalError
Python에서 중첩된 함수 범위는 지역 변수에 문제를 일으킬 수 있습니다. 다음 코드를 고려하세요.
def outer(): ctr = 0 def inner(): ctr += 1 inner()
이 코드를 실행할 때 내부 함수 내 변수 'ctr'에 대해 UnboundLocalError가 발생할 수 있습니다. 이 오류는 내부 함수가 외부 함수에 정의된 'ctr' 변수를 수정하려고 시도했지만 내부 범위 내에서 로컬 변수로 인식되지 않았기 때문에 발생합니다.
이 문제를 해결하려면 다음 두 가지 접근 방식이 있습니다.
Python 3:
Python 3에서는 nonlocal 문을 사용하여 중첩 함수 내의 비지역 변수를 수정할 수 있습니다.
def outer(): ctr = 0 def inner(): nonlocal ctr ctr += 1 inner()
Python 2:
Python 2에는 nonlocal 문이 없지만 해결 방법은 변수 이름을 직접 사용하는 대신 데이터 구조를 사용하여 변수를 보유하는 것입니다.
def outer(): ctr = [0] # Store the counter in a list def inner(): ctr[0] += 1 inner()
이 접근 방식을 사용합니다. , barename 리바인딩을 피하고 내부 함수가 의도한 변수를 수정할 수 있는지 확인하세요.
위 내용은 Python의 중첩 함수 범위에서 UnboundLocalError를 처리하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

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

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구