Home > Software design >  Python variable assignment between different methods
Python variable assignment between different methods

Time:09-16

I would like to define a class variable in Python and then modify its value calling two different methods in this way:

class MyClass:   
    # Variable x definition
    nonlocal x
    
    def Method1():
        nonlocal x
        x = 1
        print('X VALUE: ', x)
        
    def Method2():
        nonlocal x
        print('X VALUE BEFORE NEW ASSIGNMENT: ', x)
        x = 2
        print('X VALUE NEW ASSIGNMENT: ', x)
        
c = MyClass()
c.Method1()
c.Method2()

I get this error at line 10: nonlocal x 'SyntaxError: no binding for nonlocal 'x' found'. What's wrong? Thanks a lot.

CodePudding user response:

nonlocal only works in nested functions. For top-level methods like this, you could just use global.

But it would seem to make more sense in this case to make x a static/class attribute instead.

Unrelated to your question, calls to your two methods will fail because you didn't declare the self parameter on them.

CodePudding user response:

I am not sure what you try to do, since you give the functions no input the values of x will always be the same but see this:


class MyClass:   
    # Variable x definition
    def __init__(self):
        self.x = None
    
    def Method1(self):
        self.x = 1
        print('X VALUE: ', self.x)
        
    def Method2(self):
        print('X VALUE BEFORE NEW ASSIGNMENT: ', self.x)
        self.x = 2
        print('X VALUE NEW ASSIGNMENT: ', self.x)
        
c = MyClass()
c.Method1()
c.Method2()
c.Method2()

output:

X VALUE:  1
X VALUE BEFORE NEW ASSIGNMENT:  1
X VALUE NEW ASSIGNMENT:  2
X VALUE BEFORE NEW ASSIGNMENT:  2
X VALUE NEW ASSIGNMENT:  2
  • Related