반응형
오늘은 파이썬에서 모듈과 패키지를 활용하는 방법에 대해서 알아보는 시간을 갖겠다.
1. 클래스
pkg/arithmetic.py
class Arithmetic:
def __init__(self, title="Arithmetic"):
self.title = title
def sum(endNum):
return (endNum * (endNum + 1)) / 2
def sumPrint(endNum):
sum = (endNum * (endNum + 1)) / 2
print('sum => ', sum)
예시1.
- 콤마(,)를 사용해서 가져올 수 있다.
from pkg.arithmetic import Arithmetic
sum = Arithmetic.sum(10)
print('sum : ', sum)
Arithmetic.sumPrint(100)
Result
sum : 55.0
sum => 5050.0
예시2.
- import * 을 사용하면 해당 패키지의 모든 클래스, 메소드를 가져올 수 있다.
- 메모리를 많이 사용한다. (권장하지 않음)
from pkg.arithmetic import *
sum = Arithmetic.sum(10)
print('sum : ', sum)
Arithmetic.sumPrint(100)
Result
sum : 55.0
sum => 5050.0
예시3.
- as를 사용해서 import한 클래스의 명을 임의로 지정할 수 있다.
from pkg.arithmetic import Arithmetic as at
sum = at.sum(10)
print('sum : ', sum)
Arithmetic.sumPrint(100)
Result
sum : 55.0
sum => 5050.0
2. 메소드
pkg/calculations.py
def add(l, r):
return l + r
def mul(l, r):
return l * r
def div(l, r):
return l / r
pkg/prints.py
def prt1():
print("Print prt1")
def prt2():
print("Print prt2")
예시1.
- 패키지 자체를 as를 사용하여 임의로 이름을 지정할 수 있다.
import pkg.calculations as c
print("add : ", c.add(10, 100))
print("mul : ", c.mul(10, 100))
Result
add : 110
mul : 1000
예시2.
- 메소드의 명도 as를 사용하여 임의로 지정할 수 있다.
from pkg.calculations import div as d
print("div : ", int(d(100, 10)))
Result
div : 10
예시3.
- print와 같이 빌트인 함수를 확인 할 수 있다.
import builtins
import pkg.prints as p
p.prt1()
p.prt2()
print(dir(builtins))
Result
Print prt1
Print 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']
반응형
'Programming > Python' 카테고리의 다른 글
[Python] 파이썬 Comprehension 에 대해서 알아보자. (1) | 2021.10.18 |
---|---|
[Python] 파이썬 예외 종류에 대해서 알아보자. (0) | 2021.08.19 |
[Python] 파이썬 파일 쓰기(Write)에 대해서 알아보자. (0) | 2021.07.31 |
[Python] 파이썬 파일 읽기(Read)에 대해서 알아보자. (0) | 2021.07.31 |
[Python] 파이썬 클래스 상속에 대해서 알아보자. (0) | 2021.07.26 |