请问为什么在Python中查看一个类里定义的多个方法id时是相同的?

新手上路,请多包涵

Myclass类中定义了__init__、name、add三个方法,实例化对象为c1,查看三个方法的id时发现竟然是相同的,请问这是为什么?
class Myclass(object):

def __init__(self, x):
    self.x = x

def name(self):
    print self.x

def add(self):
    self.x+'world'
    print self.x

 

c1 = Myclass('hello')

print id(c1)
print id(c1.__init__)
print id(c1.name)
print id(c1.add)

输出为:
44030704
43882136
43882136
43882136

阅读 1.5k
1 个回答

这是因为 Python 会重用同一内存地址。在你指向完 id(c1.__init__) 后,c1.__init__ 不再被引用,就会被回收,接着执行 id(c1.name)c1.name 就重用了刚才 c1.__init__ 使用的内存地址,下面的 c1.add 同理。

在 Python 文档关于 id() 函数的介绍里有这么一句:

Two objects with non-overlapping lifetimes may have the same id() value

意思就是 2 个生命周期不重叠的对象,是可能拥有相同的 id 的

推荐问题