Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python object hierarchy; Referencing an owner instance?

Is there no magic python way of accessing the instance of the class that has a reference to the current self inside it? ie:

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 being the magic bullet that does not exist. Is there a feature in python for this behaviour?

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

like image 287
Zv_oDD Avatar asked Dec 16 '22 02:12

Zv_oDD


2 Answers

No, You'd have 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()
like image 54
John La Rooy Avatar answered Dec 18 '22 14:12

John La Rooy


On the second thought, what you're looking for pretty 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

Here the agent is attached to two different instances and "knows" each time which instance wants to talk to him.

like image 44
georg Avatar answered Dec 18 '22 16:12

georg