파이썬 기본 정리(7) - 모듈

yerim·2023년 1월 25일
0

파이썬 기본 정리

목록 보기
7/11

나도코딩 '파이썬 코딩 무료 강의(기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요' 정리

모듈

  • theater_module.py
##theater_module.py##
#극장에서 현금으로만 결제할 수 있고, 잔돈은 거슬러주지 않는다.
#지불해야할 금액이 얼마인지 미리 계산하는 모듈
#이것을 다른 파일에서 불러와서 사용할 수 있다.


#일반 가격 함수
def price(people):
    print("{0}명 가격은 {1}원 입니다." .format(people, people*10000))
    
#조조할인 가격 함수
def price_moring(people):
    print("{0}명 조조 할인 가격은 {1}원 입니다." .format(people, people*6000))
    
#군인 할인 가격 함수
def price_soldier(people):
    print("{0}명 군인 할인 가격은 {1}원 입니다." .format(people, people*4000))
## 모듈
#필요한 것들끼리 모아둔 것
#함수정의 or 클래스 를 모아둔 파일로 py확장자를 가짐

import theater_module   #theater_module 불러오기
theater_module.price(3) #3명 영화				3명 가격은 30000원 입니다.
theater_module.price_moring(4)  #4명 조조 영화	4명 조조 할인 가격은 24000원 입니다.
theater_module.price_soldier(5) #5명 군인 영화	5명 군인 할인 가격은 20000원 입니다.


#as 로 모듈에 대한 별명을 붙일 수 있음
import theater_module as mv     
mv.price(3)		# 3명 가격은 30000원 입니다.


#바로 모듈의 함수를 호출해서 사용할 수 있음
from theater_module import *    
price(3)		# 3명 가격은 30000원 입니다.
price_moring(4)	# 4명 조조 할인 가격은 24000원 입니다.


#모듈의 특정함수만 가져올 수 있음
from theater_module import price, price_moring  
price(5)		# 5명 가격은 50000원 입니다.
price_moring(6)	# 6명 조조 할인 가격은 36000원 입니다.


#특정함수에 대해서도 별명을 붙일 수 있음
from theater_module import price_soldier as price   
price(6)		# 6명 군인 할인 가격은 24000원 입니다.


패키지

travel 폴더의 thailand.py 와 vietnam.py

  • thailand.py
##thailand.py##
class ThailandPackage:
    def detail(self):
        print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")
        
if __name__ == "__main__":  #thailand.py 모듈에서 직접 수행
    print("Thailand 모듈을 직접 실행")
    print("이 문장은 모듈을 직접 실행할 때만 실행돼요")
    trip_to = ThailandPackage()
    trip_to.detail()
else:   #외부에서 모듈을 호출해서 수행
    print("Thailand 외부에서 모듈 호출")
  • vietnam.py
##vietnam.py##
class VietnamPackage:
    def detail(Self):
        print("[베트남 패키지 3박 5일] 다탕 효도 여행 60만원")
## 패키지
import travel.thailand    #travel 패키지
# import travel.thailand.ThailandPackage    #이렇게는 사용 불가
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()

from travel.thailand import ThailandPackage #travel 패키지 안에 있는 tailand 모듈에서 ThailandPackage 클래스 가져오기
trip_to = ThailandPackage()
trip_to.detail()

from travel import vietnam
trip_to = vietnam.VietnamPackage()
trip_to.detail()



##__all__
from travel import *
# trip_to = vietnam.VietnamPackage()
trip_to = thailand.ThailandPackage()
trip_to.detail()



##패키지, 모듈 위치 파악 방법
import inspect
import random
print(inspect.getfile(random))	#랜덤 모듈의 위치 찾기
print(inspect.getfile(thailand))


내장함수 & 외장함수

##내장함수
#input : 사용자 입력을 받는 함수
# language = input("무슨 언어 좋아하세요?")
# print("{0}은 아주 좋은 언어입니다!" .format(language))

#dir : 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시
print(dir())
import random
print(dir())
import pickle
print(dir())

print(dir(random))  #random 모듈 내에서 쓸 수 있는 함수들

lst = [1, 2, 3]
print(dir(lst)) #list에서 쓸수 있는 내용들

name = "Jim"
print(dir(name))



#외장함수
직접 import해서 사용해야 함
glob : 경로 내의 폴더 / 파일 목록 조회 (윈도우 dir)
import glob
print(glob.glob("*.py"))    #확장자가 py 인 모든 파일


os : 운영체제에서 제공하는 기본 기능. 폴더 생성 or 삭제 등
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
print("오늘 날짜는 ", datetime.date.today())

#timedelta: 두 날짜 사이의 간격
today = datetime.date.today()   #오늘 날짜
td = datetime.timedelta(days=100)   #오늘로부터 100일 후 날짜
print("우리가 만난지 100일은 ", today + td)


Quiz 10

##Quiz 10##
#프로젝트 내에 나만의 시그니처를 남기는 모듈을 만드시오
#조건 : 모듈 파일명은 byme.py로 작성
#(모듈 사용 예제)
# import byme
# byme.sign()

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


import byme
byme.sign()

byme.py

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

0개의 댓글