python 3中不同变量的id值 [英] id values of different variables in python 3

查看:232
本文介绍了python 3中不同变量的id值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够理解python的不变性(也很简单).假设我为

分配了一个数字

x = 42
print(id(x))
print(id(42))

在这两个方面,我得到的值都是

505494448

我的问题是,在环境加载之前,python解释器是否将ID分配给内存中的所有数字,字母,True/False?如果不是,则如何跟踪ID?还是我以错误的方式看待这个问题?有人可以解释一下吗?

解决方案

您看到的是调用 interning 的实现细节(内部优化).这是一种技术(由包括Java和Lua在内的多种语言的实现所使用),在可能或可行的情况下,将名称或变量作为对单个对象实例的引用的别名.

您不应依赖此行为.它不是语言正式规范的一部分,不能保证将对字符串或整数的单独文字引用进行intern,也不能保证将产生给定对象的一组给定操作(字符串或数字)与其他相同对象进行intern.

我听说C Python实现的确包含一组前一百个整数作为静态实例化的不可变对象.我怀疑其他高级语言运行库也可能包含类似的优化:大多数非平凡的代码片段经常使用前一百个整数.

就如何实现这些东西而言……对于字符串和更大的整数,Python将它们维护为字典是有意义的.因此,任何产生整数(甚至可能是浮点数)和字符串(至少足够短的字符串)的表达式都将被散列,在适当的(内部)对象字典中查找,必要时添加,然后作为对所得对象的引用返回. /p>

您可以通过将实例化包装在对自己的类静态字典的调用中来对任何类型的自定义对象进行类似的实习.

I am able to understand immutability with python (surprisingly simple too). Let's say I assign a number to

x = 42
print(id(x))
print(id(42))

On both counts, the value I get is

505494448

My question is, does python interpreter allot ids to all the numbers, alphabets, True/False in the memory before the environment loads? If it doesn't, how are the ids kept track of? Or am I looking at this in the wrong way? Can someone explain it please?

解决方案

What you're seeing is an implementation detail (an internal optimization) calling interning. This is a technique (used by implementations of a number of languages including Java and Lua) which aliases names or variables to be references to single object instances where that's possible or feasible.

You should not depend on this behavior. It's not part of the language's formal specification and there are no guarantees that separate literal references to a string or integer will be interned nor that a given set of operations (string or numeric) yielding a given object will be interned against otherwise identical objects.

I've heard that the C Python implementation does include a set of the first hundred or so integers as statically instantiated immutable objects. I suspect that other very high level language run-time libraries are likely to include similar optimizations: the first hundred integers are used very frequently by most non-trivial fragments of code.

In terms of how such things are implemented ... for strings and larger integers it would make sense for Python to maintain these as dictionaries. Thus any expression yielding an integer (and perhaps even floats) and strings (at least sufficiently short strings) would be hashed, looked up in the appropriate (internal) object dictionary, added if necessary and then returned as references to the resulting object.

You can do your own similar interning of any sorts of custom object you like by wrapping the instantiation in your own calls to your own class static dictionary.

这篇关于python 3中不同变量的id值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆