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

So sánh Namespace trong Python và C++

Namespace Python và C++ không thể so sánh trực tiếp do mô hình cơ bản khác nhau.

C++ Namespace

// a.h
namespace ns {
    struct A { ... };
    struct B { ... };
}

Using declaration: using ns::A; – cho phép viết A thay vì ns::A. Quan trọng: toàn bộ header vẫn được include và compile, bạn vẫn có thể dùng ns::B.

Using directive: using namespace ns; – đưa tất cả tên từ ns vào scope hiện tại. Namespace có thể lồng/ mở rộng ở nhiều file.

Python Import

from a import A

Chỉ đưa A vào namespace module hiện tại. a.B không visible trừ khi import thêm.

from a import *  # Tương tự using namespace (nhưng không khuyến khích)

Sự khác biệt cốt lõi

Đặc điểm C++ Namespace Python Module/Import
Cơ chế Compile-time name lookup Runtime dictionary lookup
using ns::A Unequal name, vẫn thấy ns::B from a import A – ẩn B
using namespace ns Kéo toàn bộ ns, namespace có thể mở rộng sau from a import * – snapshot tại thời điểm import
Header/Module Header include = text inclusion (preprocessing) Module = object riêng, cache trong sys.modules
ADL (Argument-Dependent Lookup) Có – tìm hàm trong namespace của argument Không có cơ chế tương đương

Best Practice

  • C++: Tránh using namespace std; ở header/global scope. Dùng using std::vector; hoặc fully qualified std::vector.
  • Python: Tránh from module import *. Dùng import module hoặc from module import specific_name.