python newbie
Neil Cerutti
horpner at yahoo.com
Fri Nov 2 11:06:17 EDT 2007
On 2007-11-02, Jim Hendricks <jim at bizcomputinginc.com> wrote:
> New to python, programming in 15 or so langs for 24 years.
>
> Couple of questions the tuts I've looked at don't explain:
>
> 1) global vars - python sets scope to the block a var is
> declared (1st set), I see the global keyword that allows access
> to global vars in a function, what I'm not clear on is does
> that global need to be declared in the global scope, or, when
> 1st set in a function where it is listed as a global, does that
> then declare the necessary global.
Names that are assigned in an assignment statement are assumed to
be defined in the current scope.
Names that are assigned to in a function are considered local
variables to that function. This allows them to be faster to
access than other attributes or global variables (which are just
attributes of a module).
def foo():
x = 7
In function foo x is a local variable. This is true even if there
is an x defined in foo's enclosing scope.
x = 5
def foo():
x = 7
x is a local variable, which shadows the module scope (global) x.
x = 5
If x is referenced, but not assigned to, then Python does not
create a local variable for it, and normal lookup rules will
cause x to be found in the enclosing scope of the bar function,
below:
def bar():
print x
In bar, the x name refers to the global x.
In order to inform Python that you would like to make
modifications to a global variable in a function, you use the
global statement to declare your intation. This overrides
Python's assumption that that name is a local variable.
x = 5
def foo2():
global x
x = 7
> 2) Everything is an object. So then, why the distinction between
> functions/variables and fields/methods. If a module is an object, would
> not every function be a method of that module and every variable be a
> field of that module?
You are almost correct. Every identifier/name in Python is
conceptually an attribute of an object. But identifiers in Python
are not typed. It is the objects that they refer to that are
typed.
--
Neil Cerutti
More information about the Python-list
mailing list