简体   繁体   English

python运行时模型不是字典的字典吗?

[英]Is not, python runtime model, dictionaries of dictionaries?

After going through this question 经过这个问题之后

globals() give the dictionary view of the global namespace( __main__ module). globals()提供全局名称空间( __main__模块)的字典视图。

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>>

Any new symbol(name), say operator added to this namespace, will become a member of that global name space. 任何新的符号(名称),例如添加到此命名空间的operator ,都将成为该全局名称空间的成员。

>>> import operator
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'operator': <module 'operator' (built-in)>, '__package__': None}
>>> globals()['operator']
<module 'operator' (built-in)>
>>> 

where operator is a new str type key, value is the module type object. 其中operator是新的str类型的键,value是module类型的对象。

further on using operator module(say __abs__ ), in current namespace, 进一步在当前名称空间中使用operator模块(例如__abs__ ),

>>> globals()['operator']['__abs__']

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    globals()['operator']['__abs__']
TypeError: 'module' object has no attribute '__getitem__'
>>> 

It says, operator module is not a dictionary because there is no attribute by name __getitem__ . 它说, operator模块不是字典,因为没有名称__getitem__属性。

But, all the code from my application(in runtime), will be part of the dictionary shown by globals() function. 但是,来自我的应用程序的所有代码(在运行时)将成为globals()函数显示的词典的一部分。

Question: 题:

Ignoring coding standards, In JavaScript, I can use dictionary notation to write my complete code, for example, 忽略编码标准,在JavaScript中,我可以使用字典符号来编写完整的代码,例如,

> window['Array']

            function Array() { [native code] }


> window['Array']['length']
1

In python, Why global namespace members(keys) are only viewed as dictionary members but not their values(like operator object)? 在python中,为什么全局名称空间成员(键)仅被视为字典成员,而不是其值(例如operator )? Despite all the subsequent code of your program, is part of that dictionary. 尽管有程序的所有后续代码,它仍是该词典的一部分。

In Python, there is a difference between attribute references , the syntax where you use dots to access attributes of objects, and subscriptions , where you use square brackets to access items of an object. 在Python中, 属性引用 (使用句点访问对象属性的语法和订阅 (使用方括号访问对象的项)的语法)之间是有区别的。

You can use this difference in your custom types by using the special methods __getitem__ (and the related methods for setting etc.) and __getattr__ (and related methods). 您可以通过使用特殊方法__getitem__ __getattr__ (以及用于设置的相关方法等)和__getattr__ (及其相关方法)来在自定义类型中使用此差异。 So you can implement your types to support both syntaxes to achieve the same; 因此,您可以实现您的类型以支持两种语法以实现相同的语法。 or you can use it to assign difference semantics to each syntax as it is the case for standard Python types. 或者,您可以使用它为每种语法分配不同的语义,就像标准Python类型一样。

As for why this distinction is made, this is simply a language design decision that was made, which ultimately makes the language more powerful. 至于为什么要做出这种区分,这仅仅是做出的语言设计决定,最终使语言变得更加强大。 For example, this allows a dictionary to have a key 'update' , when there is also an attribute—a method in this case—called dict.update . 例如,当还存在一个称为dict.update的属性(在这种情况下为方法)时,这允许字典具有键'update'

Also, not depending on the equivalence of foo.bar and foo['bar'] avoids limiting subscription keys to strings, like it is the case with JavaScript. 另外,不依赖于foo.barfoo['bar']的等效foo.bar ,可以避免将预订键限制为字符串,就像JavaScript一样。 Instead, we can use any hashable object as a key. 相反,我们可以将任何可哈希对象用作键。 This makes the dict type similar to JavaScripts newer Map type which also supports a wide range of key types. 这使得dict类型类似于JavaScript的较新Map类型 ,该Map类型还支持多种键类型。 Note that because of JavaScript's inferior syntax choices, there are explit methods get and set to access the map items. 请注意,由于JavaScript的语法选择较差,因此有一些get方法和set方法get访问地图项。

1. JS doesn't have dictionaries. 1. JS没有字典。 They are emulated by using objects. 通过使用对象来模拟它们。 What you are doing when defining a dictionary or associative array, or however you want to call it in javascript is assigning values to attributes of a new object. 定义字典或关联数组时的操作,或者想在javascript中调用的操作,是将值分配给新对象的属性。

2. Python has actual data type dictionary ie dict() which IS AN OBJECT (everything in Python is) specialized to store pairs key: value and optimized for fast access. 2. Python具有实际的数据类型字典,即dict(),它是一个对象(Python中的所有内容)都专门用于存储对key:value和为快速访问而优化的对。 This is actually a container that holds Python scopes. 这实际上是一个保存Python作用域的容器。 Ie when you call 即当您打电话时

globals()

You do not get a view of global variables. 您没有全局变量的视图。 You do get a pointer to the real global scope. 您确实获得了指向实际全局范围的指针。 So, if you say: 因此,如果您说:

globals()["abcdefgh"] = 123456

you will be able to 你将能够

print abcdefgh

because you directly inserted the variable abcdefgh into interpreters global namespace holder. 因为您直接将变量abcdefgh插入了解释器全局名称空间所有者。 This happens when you use = assignment operator automatically. 当您自动使用=赋值运算符时,会发生这种情况。

So, globals() dictionary contains real values, which are objects, but not necessarily dictionaries. 因此,globals()字典包含实际值,这些值是对象,但不一定是字典。

In JS what you describe works, because what you are actually doing is in Python this: 在JS中,您所描述的是有效的,因为您实际正在做的是在Python中执行以下操作:

class obj: pass

somevar = obj()
somevar.one = 1
somevar.two = "two"
somevar.something = "nothing"

And if you want to see them as dict, then you have to get to the somevar instance's namespace dictionary: 而且,如果您希望将它们视为dict,则必须进入somevar实例的名称空间字典:

print somevar.__dict__
somevar.__dict__["blah"] = "xxx"
print somevar.__dict__
print dir(somevar) # To see all attributes of obj()

Otherwise it is: 否则为:

print somevar
<__main__.obj instance at 0xxxxxxxxx>

And if you want the obj() instance to act as a dict() then you have to implement the dictionary's interface for it. 而且,如果您希望obj()实例充当dict(),则必须为其实现字典的接口。

In JS it is always just another object, so syntax continues to work regardless on how it was defined in the first place. 在JS中,它始终只是另一个对象,因此语法无论最初如何定义都将继续起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM