Python 11

Joy_all·2021년 3월 31일
0

Python

목록 보기
7/9

📒 모듈

  • 모듈 : 변수, 함수, 클래스를 모아놓은 파일
  • => 다른 파이썬 파일에서 실행할 수 있게 만들어진 파이썬 파일

📍 mod1.py 모듈을 가져와서 사용해보기

📍 import 모듈명 -> 해당 모듈 전체를 추가

# mod1.py

# 덧셈 연산 모듈
def add(a,b):
    return a+b
import mod1
print("모듈 실행결과 : ",mod1.add(100,200))

모듈 실행결과 : 300

from mod1 import add
print("모듈 실행결과",add(200,300))

모듈 실행결과 500

📍 from 모듈명 import 모듈함수 -> 해당 모듈의 특정 함수만 추가

# mod1.py

# 사칙 연산 모듈

def add(a,b):
    return a+b

def sub(a,b):
    return a-b

def mul(a,b):
    return a*b

def div(a,b):
    return a/b
import mod1
print("모듈 실행결과 : ",mod1.add(100,200))
print("모듈 실행결과 : ",mod1.mul(300,400))

모듈 실행결과 : 300
모듈 실행결과 : 120000

  • from mod1 import add
  • from mod1 import add,mul
from mod1 import *

print("모듈 실행결과",add(200,300))
# print("모듈 실행결과",mul(200,300)) 해당 모듈의 함수를 추가없이 사용X
print("모듈 실행결과",mul(200,300))

모듈 실행결과 500
모듈 실행결과 60000

📍 __name__ : 파이썬 내부에서 사용하는 변수

  • 해당 파일을 실행시 __main__값 저장

  • 다른 파이썬파일(모듈)에서 실행 추가한 모듈의 이름이 저장

  • 모듈(해당파일에서는) __name__ 값 : __main__

  • 모듈을 추가 파일 __name__ 값 : __main__ (X)

if __name__ == "__main__":
    print("모듈 실행!")
    print(add(10,20))
    print(div(10,30))

📍import mod2

# mod2.py
# 모듈 (변수, 클래스)

PI = 3.141592

def add(a,b):
    return a+b

class Math:
    def solv(self,r):
        return PI * (r ** 2) # 파이 곱하기 r제곱
import mod2

print("변수 값 출력 : ", mod2.PI)
print("함수 호출 : ",mod2.add(100,200))

변수 값 출력 : 3.141592
함수 호출 : 300

📍모듈안에 있는 객체를 생성후 사용

myMath = mod2.Math()
print(myMath.solv(5))

78.5398

📒 패키지

(.)연산자를 사용해서 파이썬 모듈을 관리하는 묶음

비슷한 기능들끼리 묶어서 사용

📍 패키지.모듈

# info.py
# 모듈

def sayHello():
    print("안녕하세요~!")
import itwill.info

itwill.info.sayHello()

from itwill.info import sayHello

sayHello()

안녕하세요~!
안녕하세요~!

📍 as 로 이름 줄이기

# TeamProject.py
def project():
    print("팀프로젝트 진행중!")
import itwill.class5.TeamProject
itwill.class5.TeamProject.project()
# --------------------------------------------------
from itwill.class5.TeamProject import project
project()


import itwill.class5.TeamProject as tp
itwill.class5.TeamProject.project()
tp.project()
# --------------------------------------------------
from itwill.class5.TeamProject import project as pj
project()
pj()

팀프로젝트 진행중!
팀프로젝트 진행중!
팀프로젝트 진행중!
팀프로젝트 진행중!
팀프로젝트 진행중!
팀프로젝트 진행중!

📒 내장함수 : 기본 패키지에 있는 모듈

📒 외장함수 : 외부 패키지에 있는 모듈

📍 랜덤 / 랜덤값 불러오기

import random as r

print(r.random())
print(r.randint(1,10))

0.30714512297228247
6

📍 달력 2021 불러오기

import calendar as cal
print(cal.calendar(2021))

📍 웹 브라우저

import webbrowser as web
web.open("http://www.naver.com")

네이버 오픈

# itwill/class1/hello.py

def hello():
    print("class1_hello!")
# itwill/class1/hello 모듈 실행
import itwill.class1.hello as h
h.hello()

class1_hello!

📍 패키지 생성시 자동으로 init.py 파일이 생성됨

-> __init__.py : 해당 디렉토리가 패키지의 일부다 라는 의미로 사용

3.3버전 이전의 경우 해당 파일이 없을 경우 에러 발생

profile
beginner

0개의 댓글