Python 3에서 "nonlocal"의 힘
Python 프로그래밍에서 변수는 범위에 따라 분류될 수 있습니다.
- 글로벌: 중첩을 포함하여 전체 프로그램에서 액세스 가능 기능.
- 로컬: 특정 기능이나 블록 내에서만 정의되고 액세스 가능합니다.
그러나 때로는 이러한 범위 사이의 격차를 해소해야 할 때도 있습니다. 여기서 "nonlocal" 키워드가 사용됩니다.
"nonlocal" 이해
"nonlocal"은 Python 3에서 변수에 존재하는 변수를 선언하는 데 사용됩니다. 범위가 더 넓지만 전역으로 선언되지는 않습니다. 동일한 이름을 가진 전역 변수에 영향을 주지 않고 포함된 함수에서 변수에 액세스하고 수정할 수 있습니다.
"비로컬"의 영향
차이점을 설명하려면 다음을 고려하세요. 다음 예는 "nonlocal":
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
출력:
inner: 2 outer: 1 global: 0
이 경우 inner() 함수 내의 변수 x는 external() 함수와 전역 x.
이제 다음을 사용하여 코드를 수정해 보겠습니다. "nonlocal":
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
출력:
inner: 2 outer: 2 global: 0
이 시나리오에서 "nonlocal" 키워드를 사용하면 inner() 함수 내의 x 변수가 x 변수를 참조하고 수정할 수 있습니다. 외부() 함수에서. inner() 함수 내에서 수정된 내용은 external() 함수에도 유지됩니다.
"전역"과의 차이점
"비로컬"은 "전역" 키워드와 다릅니다. 닫힌 범위의 변수에 대한 액세스 및 수정을 허용하는 반면 "전역"은 실제 전역 범위의 변수에 액세스하고 수정한다는 점에서
위 예에서 "global"을 사용하면 다음과 같은 결과가 출력됩니다.
inner: 2 outer: 1 global: 2
이 경우 inner() 함수 내의 x 변수는 전역 x 및 모든 변경 사항은 외부 변수의 값이 아닌 전역 변수의 값에 영향을 미칩니다. function.
결론
"nonlocal"은 Python 3의 닫힌 범위에서 변수에 액세스하고 수정하기 위한 강력한 메커니즘을 제공합니다. 이를 통해 전역 수정의 함정을 피할 수 있습니다. 중첩된 함수 내에 변수를 추가하고 더욱 체계적이고 모듈화된 코드 구조를 유지합니다.
위 내용은 Python의 'nonlocal' 키워드는 중첩 함수 범위의 'global'과 어떻게 다릅니까?의 상세 내용입니다. 자세한 내용은 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 최신 버전

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

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

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

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