Quirk difference between classes and functions

jfong at ms4.hinet.net jfong at ms4.hinet.net
Wed Feb 27 21:09:14 EST 2019


jf... at ms4.hinet.net於 2019年2月26日星期二 UTC+8下午4時46分04秒寫道:
> 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?

No. The LEGB apply to compile time where only name and scope are involved.

> 
> >>> 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.

At run time, the binding between name and object can be changed. It's the word "dynamic" comes from. 

What happens in class X when print(x) was encountered? I have no idea how the LEGB involves there yet:-(

--Jach

> 
> Any comment:-)?
> 
> --Jach




More information about the Python-list mailing list