Python Object Hierarchy Owner instance reference?

Isn't there a python magic way to access an instance of a class that has a reference to the current internals inside it? i.e:

class A(object):
    def __init__(self):
        self.B = B()

    def say_hi(self):
        print "Hi"

class B(object)
    def __init__(self):
        __get_owner_ref__.say_hi()

A()

      

get_owner_ref is a magic bullet that doesn't exist. Is there a function in python for this behavior?

Yes, I know I can pass a reference to the constructor, but I'm looking for a more elegant solution.

+3


source to share


5 answers


Second thought, what you're looking for closely resembles descriptors . Consider:

class Agent(object):
    def __get__(self, obj, objtype):
        print 'Agent %s called from %s ' % (id(self), obj.name)

class X(object):
    agent = Agent()

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

a = X('Foo')
a.agent

b = X('Bar')
b.agent

      



It agent

attaches here to two different instances and "knows" every time that instance wants to talk to it.

+1


source


No, you would need to do something like this



class A(object):
    def __init__(self):
        self.B = B(parent=self)

    def say_hi(self):
        print "Hi"

class B(object)
    def __init__(self, parent):
        self.parent = parent   # you don't need to do this, but it might be a good idea
        parent.say_hi()

A()

      

+3


source


No, there is no good way to do this. Pass the reference to the initializer.

To rule out questions, it might be possible in most cases to find the owner heuristically by checking the stack, something like this question . But it will be fragile, buggy and difficult to understand. And this is contrary to the "explicit" implicit philosophy.

+2


source


As far as I know, there is no such function. Also, passing it as a constructor reference and invocation is self.parent.say_hi()

much more explicit and (really) elegant. And explicit is better than implicit or using magic language functions.

+2


source


Technically, you can use sys._getframe

:

class B(object):
    def __init__(self):
        import sys
        a = sys._getframe(1).f_locals['self']
        a.say_hi()

      

But you shouldn't do that . This should lead to confusion, break new Python implementations, complicate debugging, and take a break.
There is a reason why sys._getframe

is listed in 5 years of bad ideas .

Instead, pass the reference to either the parent object or the method say_hi

.

+2


source







All Articles