osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Quirk difference between classes and functions


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