====== 모듈과 패키지 ====== * description : 모듈과 패키지 * author : 도봉산핵주먹 * email : hylee@repia.com * lastupdate : 2020-06-25 ===== 모듈과 패키지 ===== > 현재 진행중인 프로젝트 안에 참조할 파일을 만든 뒤 진행하시면 됩니다. ==== 준비 사항 ==== === 패키지 폴더와 파일 만들기 === {{:wiki:ai:python:pkgpng.png?direct&400|}} ==== 파일 내용 ==== === calculations.py === def add(l,r): return l + r def mul(l,r): return l - r def div(l,r): return l/r === 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 === prints.py === def prt1(): print("I'm Niceboy!") def prt2(): print("I'm Goodboy!") # 단위 실행 ( 독립적으로 파일 실행 ) # 이 파일이 잘 되어있는지 실행할수 있다. if __name__ == "__main__": prt1() prt2() ==== 예제 코드 ==== # Section08 # 파이썬 모듈과 패키지 # 패키지 예제1 # 상대 경로 패키지 # .. : 부모 디렉토리 # . : 현재 디렉토리 # 사용1(클래스) print("#==== 클래스 사용 예제 1 ====") from pkg.fibonacci import Fibonacci Fibonacci.fib(100) print("ex1 : ", Fibonacci.fib2(200)) print("ex1 : ", Fibonacci().title) print() # 사용2(클래스) print("#==== 클래스 사용 예제 2 ====") from pkg.fibonacci import * Fibonacci.fib(300) print("ex2 : ", Fibonacci.fib2(400)) print("ex2 : ", Fibonacci().title) print() # 사용3(클래스) print("#==== 클래스 사용 예제 3 ====") from pkg.fibonacci import Fibonacci as fb fb.fib(500) print("ex3 : ", fb.fib2(600)) print("ex3 : ", fb().title) print() # 사용4(함수) : 파일 Alias print("#==== import 함수 사용 예제 1 ====") import pkg.calculations as c print("ex4 : ", c.add(10,10)) print("ex4 : ", c.mul(10,4)) print() # 사용5(함수) print("#==== import 함수 사용 예제 2 ====") from pkg.calculations import div as d print("ex5 : ", int(d(100,10))) print() # 사용6 print("#==== import 함수 사용 예제 3 ====") import pkg.prints as p import builtins # builtins는 기본으로 import 되어 있다. p.prt1() p.prt2() print(dir(p)) print(dir(builtins)) print() ==== 실행 콘솔 ==== #==== 클래스 사용 예제 1 ==== 0 1 1 2 3 5 8 13 21 34 55 89 ex1 : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] ex1 : fibonacci #==== 클래스 사용 예제 2 ==== 0 1 1 2 3 5 8 13 21 34 55 89 144 233 ex2 : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] ex2 : fibonacci #==== 클래스 사용 예제 3 ==== 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ex3 : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] ex3 : fibonacci #==== import 함수 사용 예제 1 ==== ex4 : 20 ex4 : 6 #==== import 함수 사용 예제 2 ==== ex5 : 10 #==== import 함수 사용 예제 3 ==== I'm Niceboy! I'm Goodboy! ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'prt1', 'prt2'] ['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'] ===== Tip ===== {{tag>도봉산핵주먹 python 모듈 패키지}}