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.
source to share
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.
source to share
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.
source to share
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
.
source to share