0

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.

3
  • Please update your question with the full error traceback. Commented Sep 16, 2022 at 12:46
  • A simple class variable would seem like a better solution for this isolated example. Commented Sep 16, 2022 at 12:47
  • Even if MyClass were a function rather than a class, you would only use nonlocal in the two nested functions to refer to a variable outside their scope, not in the function whose variable is being accessed. (You would still need to ensure that x was actually defined so that nonlocal would know which scope contained x.) Commented Sep 16, 2022 at 13:00

2 Answers 2

2

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 them with the self parameter.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.