Search code examples
ooppython-2.7magic-methods

Calling a class via a proxy class returns same object


Why calling a class via proxy class returns same object ?

EDIT: I call two different attributes, but how the id is still same for two different objects ?

class A(object):
   def __init__(self):
      print "In Init"
      self.a = 40

   def __getattr__(self, attr):
      if attr in ["b", "c"]:
        return 42

       raise AttributeError("%r object has no attribute %r" % (self.__class__, attr))

 class Proxy(object):
    def __get__(self, instance, type=None, *args, **kwargs):
       return A()

 class C(object):
    tran = Proxy()

 class D(C):
    def sample(self):
       x = id(self.tran)
       y = id(self.tran)
       print x == y

  d = D()
  d.sample()

Whenever tran is accessed it returns the same object and how the ids for x and y are same ?


Solution

  • I'm pretty sure the issue you're having is becuase you're only saving the id of the objects you're getting. In CPython, the id is the memory address of the object. If the object has no references left (as is the case here after the id call ends), it will be deallocated and its memory address may be reused by a different object.

    Try keeping a reference to the actual object returned, and calling id on it later. This will make sure your two objects are alive at the same time, which will mean they'll have different ids:

    def sample(self):
        x = self.tran # don't call id yet!
        y = self.tran # we need to keep references to these objects
        print id(x) == id(y) # This will print False. You could also test "x is y".