Python 2와 Python 3의 Exec 함수 동작
exec 문은 Python 2와 Python 3의 동작에 눈에 띄는 차이가 있습니다. Python에서 2, exec는 명령문으로 작동하여 함수 내에서 지역 변수를 효과적으로 변경합니다. scope.
그러나 Python 3에서는 exec()가 함수가 됩니다. 이는 Python 2에서 가능함에도 불구하고 함수 내부의 지역 변수 수정을 방지합니다. 더욱이 이전에 선언된 변수도 수정할 수 없습니다.
locals() 함수는 지역 변수의 일방적인 업데이트만 허용합니다. 예를 들어 다음 Python 2 코드에서는
def foo(): a = 'spam' locals()['a'] = 'ham' print(a) # prints 'spam'
locals()['a']에 'ham'을 할당해도 함수 내 변수 'a'의 값에 영향을 주지 않으며, '스팸'은 계속 인쇄됩니다.
Python 2에서는 exec가 PyFrame_LocalsToFast를 사용하여 locals()에서 찾은 변수를 명시적으로 함수 locals에 복사했습니다. 그러나 Python 3에서는 이 동작이 더 이상 가능하지 않습니다.
Python 3에서 원하는 동작을 달성하려면 exec() 호출 중에 새 네임스페이스(예: 사전)를 사용해야 합니다. 이는 다음 Python 3 코드에서 확인할 수 있습니다.
def execute(a, st): namespace = {} exec("b = {}\nprint('b:', b)".format(st), namespace) print(namespace['b'])
exec() 문서에는 locals() 사용에 적용되는 제한 사항이 명시적으로 명시되어 있습니다.
"참고: 기본 로컬은 다음과 같이 작동합니다. 아래 함수 locals()에 대해 설명되어 있습니다. exec() 함수 후에 코드가 지역에 미치는 영향을 확인해야 하는 경우 기본 지역 사전에 대한 수정을 시도해서는 안 됩니다. 돌아왔습니다."
위 내용은 Python 2와 Python 3의 Exec 함수 동작은 어떻게 다릅니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonlistsCanstoreAnyDatAtype, ArrayModuLearRaysStoreOneType 및 NUMPYARRAYSAREFORNUMERICALPUTATION.1) LISTSAREVERSATILEBUTLESSMEMORY-EFFICENT.2) ARRAYMODUERRAYRAYRAYSARRYSARESARESARESARESARESARESAREDOREDORY-UNFICEDONOUNEOUSDATA.3) NumpyArraysUraysOrcepperperperperperperperperperperperperperperperferperferperferferpercient

whenyouattempttoreavalueofthewrongdatatypeinapythonaphonarray, thisiSdueTotheArrayModule의 stricttyPeenforcement, theAllElementStobeofthesAmetypecified bythetypecode.forperformancersassion, arraysaremoreficats the thraysaremoreficats thetheperfication the thraysaremorefications는

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

thescriptIsrunningwithHongpyThonversionDueCorRectDefaultTerpretersEttings.tofixThis : 1) checktheDefaultPyThonVersionUsingPyThon-VersionorPyThon3- version.2) usvirtual-ErondmentsBythePython.9-Mvenvmyenv, 활성화, 및 파괴

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
