Quirk difference between classes and functions

jfong at ms4.hinet.net jfong at ms4.hinet.net
Tue Feb 26 03:45:52 EST 2019


ast於 2019年2月26日星期二 UTC+8上午12時25分40秒寫道:
> 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 ?

May I say that the LEGB rule apply to run time, not compile time?

>>> x = 1
>>> def f():
...     print(x)
...     print(locals())
...
>>> f()
1
{}
>>> def g():
...     print(x)
...     x = 2
...     print(locals())
...
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in g
UnboundLocalError: local variable 'x' referenced before assignment
>>> class X:
...     print(x)
...     x = 2
...
1
>>>
The print(x) difference between class and function was caused by that one was executed and the other was compiled. The LEGB rule must apply to run time to make the language dynamic.

Any comment:-)?

--Jach




More information about the Python-list mailing list