gagsl-py at yahoo.com.ar
Sat Nov 11 08:18:44 CET 2006
At Saturday 11/11/2006 02:35, Camellia wrote:
>But sorry I'm so dumb I can't say I really understand,
>what do I actually do when I define a function with its name "number"?
Don't apologize, Python is a lot more dumb than you. It obeys very
simple rules (a good thing, so we can clearly understand them, once
we know them).
Recalling your previous example:
> > >> def main():
> > >> number = number()
Python first scans the source code looking for assigned-to names.
That is, names to the left of equal signs. Those names, plus the
function formal parameters, make the list of "local names". Any other
names referenced are assumed to be globals, that is, living outside
your function. (That's not entirely true but enough for now).
Notice that "number" is a local name because it's assigned to; it
doesn't matter whether a global name "number" exists or not.
When the code is executed, the "number" to the right references the
local name, which has not been assigned to yet - that's why you get
an UnboundLocalError. "number" can't be a global name when used on
the right hand side, and a local name when used on the left hand
side. It's simple: it is local, or not, but not both.
>why does a name of a function has something to do with a variable?
Notice also that it does not matter *what* kind of object a name
refers to: it may be a function, a class, an object instance,
whatever. Inside a function, by example, a local name "a" may be
bound at most to a single object at a time, it doesn't matter its
type. A local name "a" can't refer to an integer and a class at the same time.
The left hand side of an assign statement *always* uses local names,
except when you declare a name to be global by using the "global" keyword.
And notice also that I've never used the word variable.
>Oh wait can I do this in Python?:
> def b()
>so the b() will appear to be a local function which is the possible
>cause of my little own error because the compiler will interpret the
>number() as a local function but a global one?
Yes, you can. Python has "lexically nested scopes". The simple
local/global rule of above is a bit more complicated: when a name is
not local, it is searched inside the enclosing functions, then in the
containing module's global namespace, and last in the builtin names.
And yes, b is local to a, so it effectively hides any external b that
could be in outer scopes.
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
More information about the Python-list