라이브러리와 import 실행
Coddy의 Dart 개발자를 위한 Python 코스 레슨. 48개 중 29번째.
Dart 라이브러리는 import 지시문과 main 진입 함수를 사용합니다. Python 모듈은 일반적인 방식으로 처음 가져올 때 최상위 문장을 실행하고 네임스페이스를 노출합니다. main 가드는 다른 모듈이 재사용 가능한 정의를 가져올 때 명령줄 작업이 실행되지 않도록 합니다. 여러 파일로 구성된 작업에서는 상대적인 파일 구성과 내보내는 API 이름이 중요합니다. Python에서 이름을 가져온다고 해서 그 객체가 자동으로 복사되는 것은 아니며, 이후 소스 모듈에서 이름을 다시 바인딩하는 것은 공유 객체를 변경하는 것과 다른 효과를 냅니다. 헬퍼를 가져올 때 드라이버의 입력을 예기치 않게 소비하지 않도록 입력 읽기는 명시적인 실행 경로 안에 두세요.
Dart
int twice(int value) => value * 2;
void main() {
print(twice(4));
}Python
def twice(value):
return value * 2
if __name__ == '__main__':
print(twice(4))포팅 시 주의할 점
Python의 main은 이름 지정 관례이지 진입점 키워드가 아닙니다. 이 가드는 모듈의 __name__ 값을 확인하는 방식으로 작동합니다.
챌린지
초급import math를 작성하고, math.gcd(a, b)를 반환하는 common_pack(a, b) 함수와 별도의 줄에 입력된 음이 아닌 정수 두 개를 읽고 결과를 출력하는 main()이 있는 완전한 프로그램을 작성하세요. math.gcd는 최대공약수를 반환합니다. 한쪽 인수가 0이면 다른 인수를 반환하고, 둘 다 0이면 0을 반환합니다. if __name__ == "__main__":인 경우에만 main()을 호출하세요. 정의를 가져올 때는 입력을 읽거나 출력하면 안 됩니다.
잠긴 테스트 하네스는 script 또는 import가 포함된 첫 번째 줄을 읽습니다. 프로그램은 이 모드를 읽거나 처리하면 안 됩니다. 스크립트 모드에서 하네스는 __name__을 "__main__"으로 설정하고, 그러면 프로그램은 위에서 설명한 대로 읽고 출력합니다. 가져오기 모드에서는 program.py를 program 모듈로 가져오므로, 해당 파일에서 __name__ == "program"이 되고 정의를 불러오는 동안 입력이나 출력을 시도하면 오류가 발생합니다. 불러오기가 끝나면 일반적인 입력과 출력을 복원하고, 도우미 함수 호출 횟수와 음이 아닌 정수 두 개가 담긴 해당 개수만큼의 줄을 읽은 다음, 각 쌍에 대해 재사용 가능한 도우미 함수를 호출하고 쌍마다 한 줄에 도우미 함수의 결과를 출력합니다. 도우미 함수와 main 모두 메인 가드 바깥에 정의하세요. 완전한 Python 프로그램만 제출하면 됩니다. 하네스는 제공되며 잠겨 있습니다.
program.py를 편집하세요. 잠긴 driver.py는 이 파일을 스크립트로 실행하는 경우와 모듈로 가져오는 경우를 모두 테스트합니다. 드라이버는 테스트 모드 입력을 처리합니다. 프로그램은 위에서 설명한 데이터만 읽습니다.
직접 해보기
import importlib as _coddy_importlib
import runpy as _coddy_runpy
import builtins as _coddy_builtins
_coddy_input = _coddy_builtins.input
_coddy_print = _coddy_builtins.print
_coddy_mode = _coddy_input()
_coddy_import_io = []
def _coddy_forbidden_input(*args, **kwargs):
_coddy_import_io.append("input")
raise AssertionError("input during module loading")
def _coddy_forbidden_print(*args, **kwargs):
_coddy_import_io.append("print")
raise AssertionError("print during module loading")
if _coddy_mode == "script":
__name__ = "__main__"
elif _coddy_mode == "import":
__name__ = "course_module"
_coddy_builtins.input = _coddy_forbidden_input
_coddy_builtins.print = _coddy_forbidden_print
else:
raise AssertionError("invalid harness mode")
if _coddy_mode == "script":
_coddy_namespace = _coddy_runpy.run_module("program", run_name="__main__")
else:
_coddy_namespace = vars(_coddy_importlib.import_module("program"))
common_pack = _coddy_namespace['common_pack']
main = _coddy_namespace['main']
_coddy_builtins.input = _coddy_input
_coddy_builtins.print = _coddy_print
if _coddy_import_io:
raise AssertionError("module loading attempted input or output")
if _coddy_mode == "import":
if not callable(main):
raise AssertionError("main must be a callable function")
_coddy_count = int(_coddy_input())
for _coddy_index in range(_coddy_count):
_coddy_left, _coddy_right = _coddy_input().split()
_coddy_result = common_pack(int(_coddy_left), int(_coddy_right))
if type(_coddy_result) is not int:
raise AssertionError("common_pack must return an integer")
_coddy_print(_coddy_result)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Dart 개발자를 위한 Python의 모든 레슨
6신뢰할 수 있는 Python 프로그램
stdin과 정확한 형식 지정on, catch, finally, 그리고 with라이브러리와 import 실행정적 타입과 타입 힌트 비교복습: 배치 검증직접 연습해 보세요: 온라인 Python 컴파일러