为什么同一类的不同对象的方法具有相同的ID? [英] Why do methods of different objects of same class have same id?
问题描述
在下面的代码中,我不明白为什么useless_func
属于两个不同的对象时具有相同的ID?
In the following code, I don't understand why useless_func
has the same id when it belongs to two different objects?
class parent(object):
@classmethod
def a_class_method(cls):
print "in class method %s" % cls
@staticmethod
def a_static_method():
print "static method"
def useless_func(self):
pass
p1, p2 = parent(),parent()
id(p1) == id(p2) // False
id(p1.useless_func) == id(p2.useless_func) // True
推荐答案
这是我认为正在发生的事情:
Here is what I think is happening:
- 取消引用
p1.useless_func
时,将在内存中创建它的副本.此内存位置由id
返回
- 由于没有引用到刚刚创建的方法的副本,因此它被GC回收,并且内存地址再次可用
- 取消引用
p2.useless_func
时,会在相同的内存地址(可用)中创建它的副本,然后再次使用id
进行检索. - 第二个副本是GCd
- When you dereference
p1.useless_func
, a copy of it is created in memory. This memory location is returned byid
- Since there are no references to the copy of the method just created, it gets reclaimed by the GC, and the memory address is available again
- When you dereference
p2.useless_func
, a copy of it is created in the same memory address (it was available), which you retrieve usingid
again. - The second copy is GCd
如果您要运行一堆其他代码并再次检查实例方法的ID,我敢打赌id
会彼此相同,但与原始运行不同.
If you were to run a bunch of other code and check the ids of the instance methods again, I'll bet the id
s would be identical to each other, but different from the original run.
此外,您可能会注意到,在David Wolver的示例中,一旦获得对方法副本的持久引用,id
就会变得不同.
Additionally, you might notice that in David Wolver's example, as soon as a lasting reference to the method copy is obtained the id
s become different.
为证实这一理论,这是一个使用Jython的shell会话(与PyPy的结果相同),该会话未利用CPython的引用计数垃圾回收:
To confirm this theory, here is a shell session using Jython (same result with PyPy), which does not utilize CPython's reference counting garbage collection:
Jython 2.5.2 (Debian:hg/91332231a448, Jun 3 2012, 09:02:34)
[OpenJDK Server VM (Oracle Corporation)] on java1.7.0_21
Type "help", "copyright", "credits" or "license" for more information.
>>> class parent(object):
... def m(self):
... pass
...
>>> p1, p2 = parent(), parent()
>>> id(p1.m) == id(p2.m)
False
这篇关于为什么同一类的不同对象的方法具有相同的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!