python newbie

Duncan Booth duncan.booth at invalid.invalid
Fri Nov 2 11:22:41 EDT 2007


Bjoern Schliessmann <usenet-mail-0306.20.chr0n0ss at spamgourmet.com>
wrote: 

> Jim Hendricks wrote:
>> 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,
> 
> You can't just declare in Python, you always define objects (and
> bind a name to them). Yes, globals need to be defined before you
> can access them using "global".

Why not try it out for yourself (both of you). Globals do not need to be 
defined in the global scope so long as the first 'access' is to bind a 
value to the variable:

>>> aglobal

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    aglobal
NameError: name 'aglobal' is not defined
>>> def f():
	global aglobal
	aglobal = 1

	
>>> f()
>>> aglobal
1

>> 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?
> 
> They are.

A function is an attribute of the module which contains it, not a 
method. It is just like when you do:

>>> class AClass(object):
	pass

>>> def f(): print "hi"

>>> c = AClass()
>>> c.f = f
>>> c.f()
hi

'f' is an attribute of 'c', not a method of 'c'. To be a method of 'c', 
'f' would have to be an attribute of the type 'AClass'. To be a method 
of a module, a function would have to be defined in the module type, not 
a specific module instance. Modules do have a few methods, e.g. 
__repr__, but you cannot assign additional methods to the module type 
nor can you subclass it.

>>> import string
>>> string.__repr__()
"<module 'string' from 'C:\\Python25\\lib\\string.pyc'>"

The difference, of course, is that the module method __repr__ has a self 
parameter which it may use to get at the module. Functions don't have 
easy access to their module.



More information about the Python-list mailing list