Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

So sánh module, class và namespace trong Python?


Namespace là cách implement scope. Python: mỗi package, module, class, function, method function sở hữu "namespace" giải quyết tên biến. Khi function/module/package evaluated (bắt đầu thực thi), namespace tạo. Hiểu là "evaluation context". Khi function etc. kết thúc, namespace dropped, variables dropped. Có global namespace dùng nếu tên không ở local namespace.

Python cho phép đặt định nghĩa trong file dùng trong script hoặc interactive interpreter. File đó gọi module; định nghĩa từ module import vào module khác hoặc main module. Module Python là package đóng gói code tái sử dụng. Module nằm trong folder có file __init__.py. Module chứa function và class. Import module dùng keyword import.

Class định nghĩa trong main app code hoặc trong module import bởi app. Class là cốt lõi OOP chứa property và method. Tạo nhiều instance class, nhưng không tạo instance module. So sánh module như static class hoặc singleton.