命名空间提供了一种管理范围内定义的标识符的方法。换句话说,它们用于将名称映射到值(或者更准确地说是对内存位置的引用)。
例如,在命名空间的上下文中,以下表达式
x = 10
将标识符x 与保存值为10 的对象的内存位置相关联。
在 Python 中,命名空间基本上有两种“类型”; 实例和类命名空间。
Instance Namespace 管理单个对象范围内名称和值之间的映射。另一方面,源代码中定义的每个类都有一个单独的类命名空间。这种类型的命名空间处理对象的所有实例共享的所有成员。
示例
现在考虑以下示例,其中每个成员都表示它是否属于类或实例命名空间:
class Customer:
def __init__(self, first_name, last_name, email): # __init__ -> Customer Class Namespace
self._first_name = first_name # _first_name -> Instance Namespace
self._last_name = last_name # _last_name -> Instance Namespace
self._email = email # _email -> Instance Namespace
def get_full_name(self): # Customer Class Namespace
return f"{self._first_name} {self._last_name}"
class PremiumCustomer(Customer):
PREMIUM_MEMBERSHIP_COST = 4.99 # PremiumCustomer Class Namespace
class Subscription: # PremiumCustomer Class Namespace
def __init__(self, customer_email): # Subscription Class Namespace
self._customer_email = customer_email # Instance Namespace
def __init__(self, first_name, last_name, email, card_number): # PremiumCustomer Class Namespace
super().__init__(first_name, last_name, email)
self._card_number = card_number # _card_number -> Instance Namespace
def get_card_number(self): # PremiumCustomer Class Namespace
return self._card_number