为什么同一类的不同对象的方法具有相同的ID? [英] Why do methods of different objects of same class have same id?

查看:50
本文介绍了为什么同一类的不同对象的方法具有相同的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:

  1. 取消引用p1.useless_func时,将在内存中创建它的副本.此内存位置由id
  2. 返回
  3. 由于没有引用到刚刚创建的方法的副本,因此它被GC回收,并且内存地址再次可用
  4. 取消引用p2.useless_func时,会在相同的内存地址(可用)中创建它的副本,然后再次使用id进行检索.
  5. 第二个副本是GCd
  1. When you dereference p1.useless_func, a copy of it is created in memory. This memory location is returned by id
  2. 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
  3. When you dereference p2.useless_func, a copy of it is created in the same memory address (it was available), which you retrieve using id again.
  4. 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 ids 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 ids 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屋!

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