Setting a Global Default for class construction?

Chad Netzer cnetzer at mail.arc.nasa.gov
Fri Jan 31 17:46:13 EST 2003


On Fri, 2003-01-31 at 13:58, Josh English wrote:
> Here is the code that I am struggling with in a Python module:
> 
> _Thing = "it"
> 
> def SetThing(s):
> 	global _Thing
> 	_Thing = str(s)
> 
> class NewThing:
> 	def __init__(self,thing=_Thing):
> 		self.Thing = _Thing
> 
> I thought that this would work if I called:
> 
>  >>>SetThing('hallo')
>  >>>a = NewThing()
>  >>>a.Thing
> 'it'
> 
> I would expect a.Thing to return 'hallo', not 'it'. Is this possible to 
> do in Python?

It does return 'hallo' for me, in Python 2.2, 2.1, and 1.5.  Are you
sure what you posted is exactly what you have tested?  In particular,
the "global _Thing" in SetThing() is crucial.

Of course, globals are evil. :)  Couldn't you just do:

a = NewThing( 'hallo' )

and live happily (you'd have to fix the init code, btw)?


-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)







More information about the Python-list mailing list