为什么对象的id会根据python shell中的行而改变 [英] Why the id of an object would change depending on the line in the python shell
问题描述
这个问题只是出于好奇.
This questions is just out of curiosity.
虽然我在阅读 python的对象模型文档,我决定尝试使用类方法的id进行实验,并发现以下行为:
While I was reading the python's object model documentation, I decided to experiment a little with the id of a class method and found this behavior:
Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class A():
def a(self):
pass
>>> id(A().a)
54107080
>>> id(A().a)
54108104
>>> id(A().a)
54107080
>>> id(A().a)
54108104
>>>
>>> id(A().a)
54108104
>>>
>>> id(A().a)
54108104
>>> id(A().a)
54107080
>>>
该方法的ID随行的奇偶校验而改变!
The id of the method changes with the parity of the line!
我实际上想创建几个相同类的实例,看看它们是否具有相同的方法对象,并且我希望它们是完全相同的,或者每次都更改,我没想到的是方法ID与解释器行是否均匀相关!有什么想法吗?
I actually wanted to create a couple of instances of the same class and see if they had the same method object, and I expected that they would be the exact same one, or change every time, what I did not expect was that the method id would be related with the interpreter line being even or not! Any ideas?
注意:我知道文档和解释器的版本不匹配,只是我在Windows上并且只安装了3.2版本
Note: I know that there is a mismatch of version from the docs and the interpreter, it just happens that I'm on windows and I have only 3.2 installed
推荐答案
我将解释id(A().a)
行的作用:
A() # creates a new object I call a
然后
A().a # creates a function f bound to a
A.a.__get__(A(), A) # same as above
>>> A.a.__get__(A(), A)
<bound method A.a of <__main__.A object at 0x02D85550>>
>>> A().a
<bound method A.a of <__main__.A object at 0x02D29410>>
此绑定函数始终是另一个,因为它在__self__
This bound function is always another because it has another object in __self__
>>> a = A()
>>> assert a.a.__self__ is a
__self__
将作为第一个参数self
传递给函数A.a
__self__
will be passed as first argument self
to the function A.a
这是它的样子:
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class A:
def a(self):
pass
>>> id(A().a)
43476312
>>> id(A().a)
49018760
此处的ID像abab一样重复
Here the id repeats like abab
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class A:
def a(self):
pas
s
>>> id(A().a)
50195512
>>> id(A().a)
50195832
>>> id(A().a)
50195512
>>> id(A().a)
50195832
对于linux或不是我的机器,什么都不知道
For linux or what is not my machine and whatsoever I do not know
id(A().a)
将始终给出相同的结果,除非将其存储到变量中. 我不知道为什么,但是我认为这是因为性能优化. 对于堆栈上的对象,您无需在每次调用函数时为该对象分配新的空间.
will always give the same result except if you store this to a variable. I do not know why but I would think that it is because of performance optimization. For objects on the stack you do not need to allocate new space for an object every time you call a function.
这篇关于为什么对象的id会根据python shell中的行而改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!