본문 바로가기

Python Basics

[패스트캠퍼스 수강 후기] 파이썬 인강 자기계발 챌린지 10 회차 미션

패스트캠퍼스 파이썬 웹개발 올인원 패키지 후기(10)

파이썬 웹개발 올인원 패키지 10 일차 후기 겸 학습기록 입니다.

오늘은 먼저 파이썬의 모듈과 패키지에 대해서 배워 보았습니다.

모듈과 패키지가 무엇인지 알아볼까요?

파이썬 모듈, 패키지

패스트캠퍼스 파이썬 웹개발 올인원 패키지 파이썬 모듈과 패키지 학습중!

[패키지 및 모듈 생성]

간단하게 말하면 모듈은 파이썬 파일 하나를 가르키는 것.

패키지는 비슷한 종류의 모듈을 모아서 갖고 있는 하나의 디렉토리!

 

우선, 디렉토리 하나를 만들어서 패키지 폴더를 생성합니다.

강의에서는 'pkg'라는 폴더를 하나 만들었습니다.

 

그리고 'pkg'라는 폴더에 3개의 모듈을 만들었습니다.

 

(pkg/fibonacci.py)

class Fibonacci:
    def __init__(self, title="fibonacci"):
        self.title = title
    
    def fib(n):
        a, b = 0, 1
        while a < n:
            print(a, end=' ')
            a, b = b, a + b
        print()
    
    def fib2(n):
        result = []
        a, b = 0, 1
        while a < n:
            result.append(a)
            a, b = b, a + b
        return result

(pkg/prints.py)

def prt1():
    print("I'm a Son!")

def prt2():
    print("You're a Mom!")

(pkg/calculations.py)

def add(l, r):
    return 1 + r

def mul(l, r):
    return 1 * r

def div(l, r):
    return 1 / r

 

간단한 클래스와 함수를 포함하는 파이썬 파일 즉, 모듈 3개를 pkg 폴더에 저장하여 pkg 라는 패키지를 만들었습니다.

 

 

(패키지 사용 방법)

# 패키지 예제
# 상대 경로
# .. : 부모 디렉토리
# .  : 현재 디렉토리

# 사용1(클래스)
from pkg.fibonacci import Fibonacci

Fibonacci.fib(300)
print("ex1 : ", Fibonacci.fib2(400))
print("ex1 : ", Fibonacci().title)


# 사용2(클래스)
from pkg.fibonacci import *

Fibonacci.fib(500)
print("ex2 : ", Fibonacci.fib2(600))
print("ex2 : ", Fibonacci().title)


# 사용3(클래스)
from pkg.fibonacci import Fibonacci as fb

fb.fib(1000)
print("ex3 : ", fb.fib2(1600))
print("ex3 : ", fb().title)


# 사용4(함수)
import pkg.calculations as c

print("ex4 :", c.add(10, 100))
print("ex4 :", c.mul(10, 100))


# 사용5(함수)
from pkg.calculations import div as d

print("ex5 :", int(d(100, 10)))


# 사용6
import pkg.prints as p
import builtins
p.prt1()
p.prt2()
print(dir(builtins))

<Output>

0 1 1 2 3 5 8 13 21 34 55 89 144 233
ex1 :  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
ex1 :  fibonacci
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
ex2 :  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
ex2 :  fibonacci
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
ex3 :  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
ex3 :  fibonacci
ex4 : 110
ex4 : 1000
ex5 : 10
I'm a Son!
You're a Mom!
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

 

( __init__.py )

# 용도 : 해당 디렉토리가 패키지임을 선언한다.

# Python 3.x : 파일이 없어도 패키지 인식함 -> 하위호환 위해서 생성해놓는 것을 추천함.

 

(단위 실행)

def prt1():
    print("I'm a Son!")

def prt2():
    print("You're a Mom!")


# 단위 실행(독립적으로 파일 실행)
if __name__ == "__main__":
    prt1()
    prt2()

파이썬 파일 읽기, 쓰기

# 파일 읽기, 쓰기
# 읽기 모드 : r, 쓰기 모드(기존 파일 삭제) : w, 추가 모드(파일 생성 또는 추가) : a
# .. : 부모폴더, . : 현재폴더

# 파일 읽기
# 예제 1
f = open('./resource/review.txt', 'r')
content = f.read()
print(content)
print(dir(f))
# 반드시 close 리소스 반환
f.close()

print()
print()


# 예제 2
with open('./resource/review.txt', 'r') as f:
    c = f.read()
    print(c)
    print(list(c))
    print(iter(c))

print()
print()


# 예제 3
with open('./resource/review.txt', 'r') as f:
    for c in f:
        print(c.strip())

print()
print()


# 예제 4
with open('./resource/review.txt', 'r') as f:
    content = f.read()
    print(">", content)
    content = f.read() # 내용 없음
    print(">", content)

print()
print()


# 예제 5
with open('./resource/review.txt', 'r') as f:
    line = f.readline()
    # print(line)
    while line:
        print(">", line, end='')
        line = f.readline()

<Output>

The film, projected in the form of animation,
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,      
which eventually paves the path for gaining a fresh perspective on an age-old problem.      
The story also happens to centre around two parallel characters, Shundi King and Hundi King,
who are twins, but they constantly fight over unresolved issues planted in their minds      
by external forces from within their very own units.
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']


The film, projected in the form of animation,
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
which eventually paves the path for gaining a fresh perspective on an age-old problem.
The story also happens to centre around two parallel characters, Shundi King and Hundi King,
who are twins, but they constantly fight over unresolved issues planted in their minds
by external forces from within their very own units.
['T', 'h', 'e', ' ', 'f', 'i', 'l', 'm', ',', ' ', 'p', 'r', 'o', 'j', 'e', 'c', 't', 'e', 'd', ' ', 'i', 'n', ' ', 't', 'h', 'e', ' ', 'f', 'o', 'r', 'm', ' ', 'o', 'f', ' ', 'a', 'n', 'i', 'm', 'a', 't', 'i', 'o', 'n', ',', '\n', 'i', 'm', 'p', 'a', 'r', 't', 's', ' ', 't', 'h', 'e', ' ', 'l', 'e', 's', 's', 'o', 'n', ' ', 'o', 'f', ' ', 'h', 'o', 'w', ' ', 'w', 'a', 'r', 's', ' ', 'c', 'a', 'n', ' ', 'b', 'e', ' ', 'e', 'l', 'u', 'd', 'e', 'd', ' ', 't', 'h', 'r', 'o', 'u', 'g', 'h', ' ', 'r', 'e', 'a', 's', 'o', 'n', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l', ' ', 'd', 'i', 'a', 'l', 'o', 'g', 'u', 'e', 's', ',', '\n', 'w', 'h', 'i', 'c', 'h', ' ', 'e', 'v', 'e', 'n', 't', 'u', 'a', 'l', 'l', 'y', ' ', 'p', 'a', 'v', 'e', 's', ' ', 't', 'h', 'e', ' ', 'p', 'a', 't', 'h', ' ', 'f', 'o', 'r', ' ', 'g', 'a', 'i', 'n', 'i', 'n', 'g', ' ', 'a', ' ', 'f', 'r', 'e', 's', 'h', ' ', 'p', 'e', 'r', 's', 'p', 'e', 'c', 't', 'i', 'v', 'e', ' ', 'o', 'n', ' ', 'a', 'n', ' ', 'a', 'g', 'e', '-', 'o', 'l', 'd', ' ', 'p', 'r', 'o', 'b', 'l', 'e', 'm', '.', '\n', 'T', 'h', 'e', ' ', 's', 't', 'o', 'r', 'y', ' ', 'a', 'l', 's', 'o', ' ', 'h', 'a', 'p', 'p', 'e', 'n', 's', ' ', 't', 'o', ' ', 'c', 'e', 'n', 't', 'r', 'e', ' ', 'a', 'r', 'o', 'u', 'n', 'd', ' ', 't', 'w', 'o', ' ', 'p', 'a', 'r', 'a', 'l', 'l', 'e', 'l', ' ', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', ',', ' ', 'S', 'h', 'u', 'n', 'd', 'i', ' ', 'K', 'i', 'n', 'g', ' ', 'a', 'n', 'd', ' ', 'H', 'u', 'n', 'd', 'i', ' ', 'K', 'i', 'n', 'g', ',', '\n', 'w', 'h', 'o', ' ', 'a', 'r', 'e', ' ', 't', 'w', 'i', 'n', 's', ',', ' ', 'b', 'u', 't', ' ', 't', 'h', 'e', 'y', ' ', 'c', 'o', 'n', 's', 't', 'a', 'n', 't', 'l', 'y', ' ', 'f', 'i', 'g', 
'h', 't', ' ', 'o', 'v', 'e', 'r', ' ', 'u', 'n', 'r', 'e', 's', 'o', 'l', 'v', 'e', 'd', ' ', 'i', 's', 's', 'u', 'e', 's', ' ', 'p', 'l', 'a', 'n', 't', 'e', 'd', ' ', 'i', 'n', ' ', 't', 'h', 'e', 'i', 'r', ' ', 'm', 
'i', 'n', 'd', 's', '\n', 'b', 'y', ' ', 'e', 'x', 't', 'e', 'r', 'n', 'a', 'l', ' ', 'f', 'o', 'r', 'c', 'e', 's', ' ', 'f', 'r', 'o', 'm', ' ', 'w', 'i', 't', 'h', 'i', 'n', ' ', 't', 'h', 'e', 'i', 'r', ' ', 'v', 'e', 'r', 'y', ' ', 'o', 'w', 'n', ' ', 'u', 'n', 'i', 't', 's', '.']
<str_iterator object at 0x00000284711385B0>


The film, projected in the form of animation,
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
which eventually paves the path for gaining a fresh perspective on an age-old problem.
The story also happens to centre around two parallel characters, Shundi King and Hundi King,
who are twins, but they constantly fight over unresolved issues planted in their minds
by external forces from within their very own units.


> The film, projected in the form of animation,
imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
which eventually paves the path for gaining a fresh perspective on an age-old problem.
The story also happens to centre around two parallel characters, Shundi King and Hundi King,
who are twins, but they constantly fight over unresolved issues planted in their minds
by external forces from within their very own units.
>


> The film, projected in the form of animation,
> imparts the lesson of how wars can be eluded through reasoning and peaceful dialogues,
> which eventually paves the path for gaining a fresh perspective on an age-old problem.
> The story also happens to centre around two parallel characters, Shundi King and Hundi King,
> who are twins, but they constantly fight over unresolved issues planted in their minds
> by external forces from within their very own units.

 

파이썬의 모듈과 패키지 개념에 대해 확실하게 알게 된 것 같습니다.

그리고 파일을 읽는 법에 대해서도 배웠는데요,

다음 시간에는 파일 쓰기 방법에 대해서 배울 것 같네요!

 

패스트캠퍼스 파이썬 인강 자세한 내용은 아래 링크를 참고해 주세요!

 

https://bit.ly/2WG0IXN