python - 对象的属性集和它的命名空间有什么区别?

标签 python oop object namespaces

一个对象的属性集形成一个命名空间。要访问该属性,您必须指定命名空间:obj.attr。这是否意味着对象的属性只是在特定 namespace (对象名称)中定义的名称?或者有区别吗?例如,对模块中名称的引用是属性引用:在表达式 modname.function 中,modname 是一个模块对象,funcname 是一个属性它的 ( see: 9.2 ) 但是当你像下面这样定义一个函数时,函数的命名空间和它的属性之间有明显的区别:

>>> def aFunction():
    x=1
    y=2
    z=3
    #three names have been defined in the local namespace,
    #but aren't considered to be attributes of aFunction from what I understand.

我真的很困惑。有人可以对此进行详细说明并解释对象的命名空间及其属性之间的区别吗?

最佳答案

请允许我引用文档:

A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change in the future. Examples of namespaces are: the set of built-in names (containing functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace. The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces;

因此,@user2357112 支持 Monica 在评论中说:

There's more than one way a namespace can be conceptually associated with an object.

肯特约翰逊也 talked关于它:

Another way to think of it is, a namespace is a place where names are looked up. When you use a bare name (not an attribute), it is looked up in the local namespace, then the global namespace, then the built-in namespace. For example:

y = 2  # Defines y in the global (module) namespace

def f():
  x = 1 # Defines x in the local (function) namespace

  # This looks up x, finds it in the local namespace
  # looks up abs, finds it in the built-in namespace
  print abs(x)

  # This looks up y, finds it in the global namespace
  print y

Note that none of the above namespaces have a related __dict__ attribute, the namespace mappings are not stored that way.

Objects also define a sort of namespace, where attributes are defined and looked up. The dict containing the namespace of an object is itself stored as an attribute of the object, called __dict__. So __dict__ is an implementation detail of the way object attributes are stored.

As a beginner, it is important to understand the way bare names are looked up (local, global, built-in namespace) and a bit about the way attributes work. You don't have to be concerned with the implementation details such as __dict__.

您可以使用 dir() 探索不同的命名空间功能,其中:

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

def foo(a):
    if a == 3:
        b = 1
    else:
        c = 1
    print("Local function namespace: ", dir())


a = 2
b = 3
foo.custom_attr = "some attr"
foo(a)
foo(b)
print("Global namespace: ", dir())
print("foo object namespace via dir: ", dir(foo))
print("foo object namespace via __dict__: ", foo.__dict__)
print("Built-in namespace: ", dir(__builtins__))

输出:

Local function namespace:  ['a', 'c']
Local function namespace:  ['a', 'b']
Global namespace:  ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'foo']
foo object namespace via dir:  ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'custom_attr']
foo object namespace via __dict__:  {'custom_attr': 'some attr'}
Built-in namespace:  ['ArithmeticError', 'AssertionError', 'AttributeError', [...]

关于python - 对象的属性集和它的命名空间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63595416/

相关文章:

python - 从多个网址(使用 beautifulsoup)提取标题和表主体到数据帧

python - 方法需要 'double *' 类型的参数?

python - 如何在 virtualenv 中安装 python3-gi?

python - 如何向类中添加前/后方法。 Python

javascript - 有没有办法使用 Firebug 查看 [object][object] 中包含的信息?

python - 在 TensorFlow 中使用多对多 LSTM 进行视频分类

javascript - 在方法中访问属性

php - 动态调用类方法参数

java - 我在java中的For循环做错了什么?

arrays - 从数组创建对象