Quirk difference between classes and functions

ast none at gmail.com
Mon Feb 25 11:25:22 EST 2019


Hello

I noticed a quirk difference between classes and functions

 >>> x=0
 >>>
 >>> class Test:
         x = x+1
         print(x)
         x = x+1
         print(x)

1
2
 >>> print(x)
0

Previous code doesn't generate any errors.
x at the right of = in first "x = x+1" line is
the global one (x=0), then x becomes local

within a function, this is not allowed

 >>> x = 0
 >>>
 >>> def f():
         x = x+1

 >>> f()
UnboundLocalError: local variable 'x' referenced before assignment

Since x is written inside the function, it is considered as a local
variable and x in x+1 is undefined so this throw an exception

Any comment ?



More information about the Python-list mailing list