gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:19:41 25 4
gpt4 key购买 nike

一个对象的属性集形成一个命名空间。要访问该属性,您必须指定命名空间: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 arelooked up. When you use a bare name (not an attribute), it is looked upin the local namespace, then the global namespace, then the built-innamespace. 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 definedand looked up. The dict containing the namespace of an object is itselfstored as an attribute of the object, called __dict__. So __dict__ is animplementation detail of the way object attributes are stored.

As a beginner, it is important to understand the way bare names arelooked up (local, global, built-in namespace) and a bit about the wayattributes work. You don't have to be concerned with the implementationdetails 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com