Rusheng Zhang
Rusheng Zhang

Reputation: 85

how to get the object from its attribute in python?

I want to do something like this:

class B():
    def __init__(self,c):
        self.c=c
    def getA(self):
        #this is what I want
class A():
    def __init__(self,d):
        self.b = B(d)

a = A(d)

what I want is that when I perform

a.b.getA()

I can get the object a that use this method by its attribute b. I can't pass any new variable to the function because this in implementation is a class written by other people that changing the input variables means changing a lot of stuff.

Can anyone help?

Upvotes: 1

Views: 198

Answers (1)

Since it seems that you construct the B instance within the A constructor, then give your B instance a reference to the A instance:

class B():
    def __init__(self, c, a):
        self.c = c
        self.a = a
    def getA(self):
        return self.a

class A():
    def __init__(self, d):
        self.b = B(d, self)

a = A(d)

It is possible under certain Python implementations to sometimes find an instance using the gc.get_referrers, but as the documentation says, using it should be avoided "for any purpose other than debugging.":

import gc

class B():
    def __init__(self,c):
        self.c = c

    def getA(self):
        for i in gc.get_referrers(self):
            if not isinstance(i, dict):
                continue

            for j in gc.get_referrers(i):
                if isinstance(j, A) and getattr(j, 'b', None) is self:
                    return j

        return

class A():
    def __init__(self,d):
        self.b = B(d)

a = A(42)
print(a.b.getA() is a)

The first get_referrers call will find among others, the __dict__ of the A instance; this would probably be of type dict; we then go through all the objects of the dictionaries referring to self, and if any of these is of type A, and it has attribute b whose value is self, we return that object.

Thus the clause print(a.b.getA() is a) shall print true.

But seriously, don't use this code.

Upvotes: 1

Related Questions