728x90

모듈(module) : 각종 변수, 함수, 클래스를 담고 있는 파일이고, 패키지(package)는 여러 모듈을 묶는 것이다.
파이썬을 설치할 때 다양한 모듈과 패키지가 기본으로 설치된다.
패키지를 만들어서 사용할 수도 있고, 다른 사람이 만든 패키지를 설치해서 쓸 수도 있다.



# 모듈 만들기
# 1. animal 폴더를 만든다.
# 2. animal 폴더에 cat.py 라는 파일을 만들고, 클래스를 정의한다.
# 3. animal 폴더에 dog.py 라는 파일을 만들고, 클래스를 정의한다.
# 4. animal 폴더에 __init__.py 라는 파일을 만들고, 현재 폴더에 있는 파일의 모듈 가져오기를 한다.

# cat.py 파일
class Cat:
    def hi(self):
        print("야옹")

# dog.py 파일

class Dog:
    def hi(self):
        print("멍멍")

# __init__.py 파일
from .cat import Cat  # . : 이 폴더에 있는 cat.py 라는 파일에서 Cat 이라는 클래스를 가져와라.
from .dog import Dog  # . : 이 폴더에 있는 dog.py 라는 파일에서 Dog 이라는 클래스를 가져와라.
        



# 모듈 가져오기 : import moduleName1, moduelName2
from animal import dog # animal 패키지에서 dog 라는 모듈을 불러와.
from animal import cat # animal 패키지에서 cat 이라는 모듈을 불러와.

d = dog.Dog()  # instance
d.hi()

c = cat.Cat()
c.hi()

from animal import *  # animal 패키지가 갖고 있는 모듈을 모두 불러와.
d = Dog()
d.hi()

c = Cat()
c.hi()

import math
print(math.pi)
print(math.sqrt(4.0))  # math 모듈의 제곱근 함수 sqrt
print(math.sqrt(2.0))

#print(math.sqrt(2.0, 2)) # 인수가 1개 이어야 하는데 일부러 2개를 입력하면...

# from import로 모듈의 일부만 가져오기
from math import pi  # math 모듈에서 pi 함수만 가져와라.
print(pi)

from math import sqrt  # math 모듈에서 sqrt 함수만 가져와라.
print(sqrt(2.0))

from math import sqrt as s  # math 모듈에서 sqrt 함수를 가져오면서 이름을 s로 지정해라.
print(s(3.0))

from math import *  # math 모듈의 모든 변수, 함수, 클래스를 가져와라.
print(pi)
print(sqrt(5.0))


import urllib.request  # urllib 패키지의 request 모듈 가져와라.
urllib.request.request = urllib.request.urlopen("http://www.google.co.kr")
print(urllib.request.request.status)


블로그 이미지

Link2Me

,