[Python] 나도코딩 기본편 - (8)

Updated:

유튜브 나도코딩 무료 강의를 통해 학습한 내용을 정리해서 올리고 있습니다.

실습과정에서 필요에 따라 일부 강의 내용의 누락 및 추가, 수정사항이 있습니다.

퀴즈의 경우, 유튜브 풀이와 상이할 수 있습니다.


모듈

import theater_module # 모듈의 class, function 등 사용 가능
import theater_module as mv # 별칭
from theater_module import * # 전체 가져와서 모듈명 안적고 함수 등 사용 가능
from theater_module import price, price_morning # 일부만
from theater_module import price_soldier as F1 # 함수에 별칭
  • theater_module이라는 특정 파이썬 파일을 모듈을 생성하였고 import를 통해 현재 파이썬 파일에서 사용 가능하다.

  • 모듈 별칭, 모듈 내 함수만 불러오기 등이 가능하다.

패키지

import travel.thailand # 패키지.모듈
# from travel.thailand import ThailandPackage as TP

trip_to = travel.thailand.ThailandPackage()
trip_to.detail()

# from 패키지 import * 하려면 all에 설정해라
from travel import *
trip_to = thailand.ThailandPackage()
trip_to.detail()
[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원
[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원
  • 패키지는 모듈의 집합체로 패키지 전체를 불러올 수도 있고 일부 모듈만 불러올 수도 있다.

모듈 위치 확인

import inspect
import random
print(inspect.getfile(random))
print(inspect.getfile(thailand))
  • inspect 패키지의 getfile() 함수로 모듈이 저장된 위치를 알 수 있다.

dir 함수

import random
print(dir())
print(dir(random))
  • dir()에 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시한다.

  • 출력 결과가 많아서 결과창은 생략하였다.

glob 패키지

import glob
print(glob.glob("*py")) # 확장자가 py 인 모든 파일
  • 경로 내의 폴더와 파일 목록을 조회 가능한 패키지이다.

  • 결과창은 생략하였다.

os 패키지

import os
print(os.getcwd()) # 현재 디렉토리

folder = "sample_dir"

if os.path.exists(folder):
    print("이미 존재하는 폴더")
    os.rmdir(folder)
    print(folder, "폴더를 삭제하였습니다.")
else:
    os.makedirs(folder) # 폴더 생성
    print(folder, "폴더를 생성하였습니다.")    

print(os.listdir())
  • 운영체제에서 제공하는 기본 기능을 가지고 있는 패키지이다.

  • 결과창은 생략하였다.

time 패키지

import time
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S"))


import datetime
today = datetime.date.today()
td = datetime.timedelta(days=100)
print("알게 된지 100일은", today + td)
time.struct_time(tm_year=2021, tm_mon=6, tm_mday=9, tm_hour=2, tm_min=7, tm_sec=39, tm_wday=2, tm_yday=160, tm_isdst=0)
2021-06-09 02:07:45
알게 된지 100일은 2021-09-17
  • 시간에 관련된 다양한 함수가 저장된 패키지이다.

Quiz 10

프로젝트 내에 나만의 시그니처를 남기는 모듈을 만드시오

조건: 모듈 파일명은 byme.py

출력 예제

이 프로그램은 0000에 의해 만들어졌습니다.

유튜브: http://youtube.com

이메일: 0000@0000.com

import byme
byme.sign()
이 프로그램은 나도코딩에 의해 만들어졌습니다.
유튜브 : http://youtube.com)
이메일 : nadocoding@gmail.com

Leave a comment