Trong Python, module và package là hai khái niệm quan trọng giúp tổ chức mã nguồn và tái sử dụng các thành phần của chương trình. Dưới đây là sự giải thích chi tiết về chúng:
.py
. Ví dụ, nếu bạn có một tệp tin tên là my_module.py
, nó có thể chứa:# my_module.py def greet(name): return f"Hello, {name}!" value = 42
# main.py import my_module print(my_module.greet("Alice")) # Output: Hello, Alice! print(my_module.value) # Output: 42
__init__.py
. Tệp tin này cho Python biết rằng thư mục đó nên được coi là một package.__init__.py
. Ví dụ, cấu trúc package có thể như sau:my_package/ __init__.py module1.py module2.py
__init__.py
: Tệp __init__.py
có thể để trống hoặc chứa mã để khởi tạo package.# my_package/module1.py def hello(): return "Hello from module1!" # my_package/module2.py def greet(): return "Greetings from module2!" # main.py from my_package import module1, module2 print(module1.hello()) # Output: Hello from module1! print(module2.greet()) # Output: Greetings from module2!
__init__.py
, giúp tổ chức các module một cách có hệ thống.