A newbie quesiton: local variable in a nested funciton
jfong at ms4.hinet.net
jfong at ms4.hinet.net
Sun Dec 27 20:02:39 EST 2015
Chris Angelico at 2015/12/27 UTC+8 2:32:32PM wrote:
> On Sun, Dec 27, 2015 at 3:11 PM, <jfong at ms4.hinet.net> wrote:
> > Last night I noticed that Python does not resolve name in "def" during import, as C does in the compile/link stage, it was deferred until it was referenced (i.e. codes was executed). That's OK for Anyway codes has to be debugged sooner or later. I just have to get used to this style.
> >
> > But check these codes, it seems not.
> > -------
> > x = 1 # a global variable
> > print(x)
> >
> > class Test:
> > x = 4 # a class attribute
> > print(x)
> > def func(self):
> > print(x)
> >
> > x1 = Test()
> > x1.x = 41 # a instance's attribute
> > x1.func() # it's 1 but 41 was expect:-(
> > --------
> >
> > --Jach
>
> When you import this module, it runs all top-level code. So the
> 'print' at the top will happen at import time.
>
> Among the top-level statements is a class definition. When that gets
> run (to construct the class itself - distinct from instantiating it,
> which happens further down), it builds a class by executing all the
> statements in it, in order. That results in that value of x being
> printed, and then defines a function.
>
> The function definition is being run at time of class construction,
> and it creates a new attribute on the Test class. At that time, the
> function body isn't actually executed (as you might expect). However,
> it's worth noting that the function does not inherit class scope. The
> unadorned name 'x' references the global. If you want to access
> class-scope names from inside methods, you need to say 'self.x', which
> also applies to instance attributes. That's what would do what you
> expect here.
>
> ChrisA
Yea, right, it's in a method, not a function. A stupid mistake I had made:-(
Thanks for your kindly patient with me, and Happy New Year to you:-)
--Jach
More information about the Python-list
mailing list