0

All the id() in the following python program prints the same value. I had thought different member functions are different objects therefore id() should return different values. Why does id() return the same values?

class A():
    def x(self):
            print 'x'
    def __y(self):
            print 'y'
    def y(self):
            self.__y()

class B(A):
    def x(self):
            self.jj = 20
            print 'bx'
    def __y(self):
            self.sj = 20
            print 'by'
            print 'by'

ta = A()
tb = B()

ta.x()
ta.y()
ta._A__y()

tb.x()
tb._A__y()
tb._B__y()
tb.y()

print id(ta.x)
print id(ta.y)
print id(ta._A__y)
print id(tb.x)
print id(tb._A__y)
print id(tb._B__y)
print id(tb.y)

The next question (actually that was the original question I had) would be, how to examine if tb._A__y and tb.y really invokes the same function. I had though using id() will tell me the answer if id() returns the address of a function. But now I udnerstand it doesn't work that way in Python.

yeeha
  • 139
  • 2
  • 8
  • 1
    From the docs: [Two objects with non-overlapping lifetimes may have the same id() value.](https://docs.python.org/2/library/functions.html#id) – user2357112 Jun 03 '14 at 04:38
  • It is still not clear what objects are created when I write "tb._A__y" and "tb._B__y". Why their lifetimes don't overlap? aren't ta and tb are always live until the end of the program? if tb is still alive, then its member functions are live too. so the question is why their lifetives don't overlap? anybody knows the python source code related with id()? I am interseted in take a look. thanks for the tips. – yeeha Jun 03 '14 at 04:43
  • 2
    A new method object is created every time the method is accessed. Python doesn't keep them around. – user2357112 Jun 03 '14 at 04:45
  • See http://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object – fr1tz Jun 03 '14 at 04:52
  • @user2357112 what do you mean by "new method object" ? any doc about this? it has been my guess that seems every member function call is through a single object (not like different functions in C++). But I need some doc help me to understand it. thx – yeeha Jun 03 '14 at 04:52
  • Also http://stackoverflow.com/questions/16727490 – Andrew Clark Jun 03 '14 at 04:54
  • 1
    @yeeha when you reference a bound class method via 'classinstance.method' python creates a new object. After this call, it discards it. Thus the same space in memory can be reused (and you get the same 'id') – fr1tz Jun 03 '14 at 04:54
  • thx for the help. I will take a look at the given reference. The next question (actually that was the original question I had) would be, how to examine if tb._A__y and tb.y really invokes the same function. I had though using id() will tell me the answer if id() returns the address of a function. But now I udnerstand it doesn't work that way in Python. – yeeha Jun 03 '14 at 05:01

0 Answers0