Instance vs Class variable oddity

jfong at ms4.hinet.net jfong at ms4.hinet.net
Sat May 18 03:33:41 EDT 2019


Chris Angelico於 2019年5月18日星期六 UTC+8下午3時09分37秒寫道:
> On Sat, May 18, 2019 at 1:51 PM <jfong at ms4.hinet.net> wrote:
> >
> > Correct me if I am wrong, please.
> >
> > I always think that the LEGB rule (e.g. the namespace to look up for) was applied at compile-time, only the binding was resolved "dynamically" at run-time. For example:
> >
> > def foo():
> >     print(x)
> >
> > foo() will cause a NameError. But after
> >
> > x = 5
> >
> > foo() will run correctly.
> 
> This is correct; however, this function will fail with UnboundLocalError:
> 
> x = 1
> def foo():
>     print(x)
>     x = 2
> 
> Function locals ARE locked in at compile time.
> 
> ChrisA

Thank you. This example proves that the LEGB rule was applied at compile-time, and it fails to resolve the binding at run-time.

--Jach



More information about the Python-list mailing list