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.
MyClasswere a function rather than a class, you would only usenonlocalin 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 thatxwas actually defined so thatnonlocalwould know which scope containedx.)