Module คือไฟล์ .py ที่มี Definitions (ฟังก์ชัน คลาส ตัวแปร) นำไป Import ใช้ได้
สร้างโมดูล fibonacci.py
def fib(n):
"""Print Fibonacci series up to n"""
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a + b
print()
def fib2(n):
"""Return Fibonacci series up to n as list"""
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
return result
Import และใช้งาน
>>> import fibonacci
>>> fibonacci.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibonacci.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
โครงสร้าง Package (หลายโมดูล)
my_package/
__init__.py
core.py
helpers.py
__init__.py ทำให้โฟลเดอร์กลายเป็น Package สามารถ Import my_package.core ได้
อ่านเพิ่ม: Python Modules Tutorial