728x90
반응형
45. 모듈과 패키지 만들기
45.1 모듈
# square.py
base = 2
def square(n):
return base ** n
# import square
print(square.base)
print(square.square(10))
==========================
2
1024
# from square import base, square
print(base)
print(square(10))
==========================
2
1024
# person.py
class Person:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
def greeting(self):
print('hello, it\'s', self.name)
# import person
maria = person.Person('maria', 20, 'seoul songpa')
maria.greeting()
==========================
hello, it's maria
45.2 모듈의 시작점
# hello.py
print('module start')
print('module.py __name__', __name__)
print('module end')
# main.py
import hello
print('main.py __name__', __name__)
module start
module.py __name__ hello
module end
main.py __name__ __main__
==========================
module start
module.py __name__ hello
module end
main.py __name__ __main__
# calc.py
def add(a, b):
return a + b
def mul(a, b):
return a * b
if __name__ == '__main__':
print(add(10, 20))
print(mul(10, 20))
=================================
30
200
❯ python3 calc.py
30
200
# main2.py
import calc
lineBoard = '\n==========================\n'
print(lineBoard)
print(calc.add(50, 60))
print(calc.mul(50, 60))
==========================
110
3000
45.3 패키지
from calcpkg.operation import add
import calcpkg.geometry
import underline
underline
print(calcpkg.operation.add(10, 20))
print(calcpkg.operation.mul(10, 20))
print(calcpkg.geometry.triangle_area(30, 40))
print(calcpkg.geometry.rectangle_area(30, 40))
==========================
30
200
600.0
1200
from calcpkg.operation import add, mul
from calcpkg.geometry import triangle_area, rectangle_area
import underline
underline
print(add(10, 20))
print(mul(10, 20))
print(triangle_area(30, 40))
print(rectangle_area(30, 40))
==========================
30
200
600.0
1200
import sys
print(sys.path)
==========================
['/Users/cheryl/Documents/workspace/practice2022/python-coding',
'/Users/cheryl/Documents/workspace/practice2022/python-coding',
'/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_display',
'/Users/cheryl/.pyenv/versions/3.10.0a5/lib/python310.zip',
'/Users/cheryl/.pyenv/versions/3.10.0a5/lib/python3.10',
'/Users/cheryl/.pyenv/versions/3.10.0a5/lib/python3.10/lib-dynload',
'/Users/cheryl/.pyenv/versions/3.10.0a5/lib/python3.10/site-packages',
'/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend']
45.4 패키지에서 from import 응용
from calcpkg import *
print(add(10, 20))
print(mul(10, 20))
print(triangle_area(30, 40))
print(rectangle_area(30, 40))
==========================
30
200
600.0
1200
728x90
반응형
'Language > Python' 카테고리의 다른 글
[코딩도장]44. 모듈과 패키지 사용 (0) | 2022.04.19 |
---|---|
[코딩도장]43.정규표현식 (0) | 2022.04.14 |
[코딩도장]42.데코레이터 (0) | 2022.04.12 |
[코딩도장]41.코루틴 (0) | 2022.04.11 |
[코딩도장]40.제너레이터 (0) | 2022.04.06 |