Package trong Python giúp tổ chức module theo phân cấp. Yêu cầu file __init__.py trong thư mục.
Tạo package đơn giản
Cấu trúc:
university/ __init__.py student.py faculty.py testing.py
student.py, faculty.py định nghĩa class. testing.py import và sử dụng:
from student import Student
from faculty import Faculty
student = Student({'name':'John','gender':'Male','year':'3'})
faculty = Faculty({'name':'Emma','subject':'Programming'})
print(student.get_student_details())
print(faculty.get_faculty_details())
Subpackage
Cấu trúc lồng:
university/
__init__.py
student/
__init__.py
main.py
testing.py
Import: from student.main import Student (dùng dấu chấm).
Kết luận
Package tổ chức code rõ ràng, dễ bảo trì, mở rộng.