Search code examples
pythonclassinstances

Access to the methods of the class from which it was instantiated another class


I'm trying to access the methods of the class from which it was instantiated another class, I mean, accessing to the "parent" instance without creating a new instance of it.

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

class B():
    def __init__(self):  
        ...     
    def function1(self):  
        ...  
    def function2(self):  
        C().run() # I need to use class C functionalities
        ...  

class C():  
    def __init__(self):  
        ...  
    def run(self):  
        classB.function1() #I can't access to these methods without instantiating again class B  


# I have to execute:
>>> a = A()
>>> a.b_instance.function2()

Sorry if I have not explained well, is a bit confusing. If you need any clarification do not hesitate to ask.

EDIT.

In class C a specific handling of the execution of class B methods is done. Is not possible to instanciate again inside C because class B contains the initialization of hardware.


Solution

  • It's still not clear what exactly you're trying to achieve, but here's one fix:

    class A():  
        def __init__(self):
            ...  
            b_instance = B()  
            ...
    
    class B():
        def __init__(self):  
            ...     
        def function1(self):  
            ...  
        def function2(self):  
            C().run(self) # pass class B instance to C instance run method
            ...  
    
    class C():  
        def __init__(self):  
            ...  
        def run(self, classB): # note additional parameter
            classB.function1()
    

    However, note that this represents a very high level of coupling between your various classes, which seems suspicious to me and may indicate a deeper flaw in your design.