Search code examples
pythonclassglobal-variables

Python local variable defined in an enclosing scope referenced before assignment in multiple functions


I have the following code:

class MyFirstClass:
    
    def myDef(self):
        global x, y
        x = 'some_str'
        y = 0

class MySecondClass:

    def myOtherDef(self):
        for i in range(10):
            y += 1
            if y % 2 == 0:
                y = 0
                x = 'new_str'

However, y += 1 errors with local variable 'y' defined in an enclosing scope on line 4 referenced before assignment

How can I re-assign variable y in the new class?


Solution

  • There are 2 issues with this. The first is that you need to define x and y as members of MyFirstClass, not as globals in a method. You won't be able to access them that way. The second is that you need an instance of MyFirstClass in MySecondClass:

    class MyFirstClass:
        x = 'some_str'
        y = 0
            
    class MySecondClass:
        myFirstClass = MyFirstClass()
        def myOtherDef(self):
            for i in range(10):
                self.myFirstClass.y += 1
                if self.myFirstClass.y % 2 == 0:
                    self.myFirstClass.y = 0
                    self.myFirstClass.x = 'new_str'
                    print(self.myFirstClass.x)
    
    
    mySecondClass = MySecondClass()
    mySecondClass.myOtherDef()
    

    Output:

    new_str
    new_str
    new_str
    new_str
    new_str