pythonoopclassobjectrelationship

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.


Solution

  • What you're looking for pretty closely resembles descriptors. Consider:

        class Agent(object):
            def __get__(self, obj, objtype):
                print f'Agent {id(self)} called from {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.