slalomchip
slalomchip

Reputation: 909

Call a Python Main Class Instance from Another Class Without Global

In the code below, an instance of class A is created in main(). I want to reference that instance from class B without needing to declare a as global. How can I do this? (Note - if, you run this script and then run it a second time with global a deleted or commented out, make sure the variables are cleared or restart the kernel before running it. Otherwise, at least in Spyder, the script appears to run OK.)

class A():
    
    def __init__(self):
        pass
    
    def start_the_process(self):
        self.b = B()
        self.b.add_values(2, 3)
        
    def print_result(self, result):
        print(result)

class B():
    
    def __init__(self):
        pass
    
    def add_values(self, val1, val2):    
        a.print_result(val1 + val2)
        
def main():
    global a
    a = A()
    a.start_the_process()

if __name__ == '__main__':
    main()

Upvotes: 0

Views: 1054

Answers (1)

Barmar
Barmar

Reputation: 781741

The B class should receive the A object as a parameter, and save it as an attribute.

class A():
    
    def __init__(self):
        pass
    
    def start_the_process(self):
        self.b = B(self)
        self.b.add_values(2, 3)
        
    def print_result(self, result):
        print(result)

class B():
    
    def __init__(self, a):
        self.a = a
    
    def add_values(self, val1, val2):    
        self.a.print_result(val1 + val2)
        
def main():
    a = A()
    a.start_the_process()

if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions