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

查看:25
本文介绍了为什么同一个类的不同对象的方法有相同的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天全站免登陆