Functions as Objects, and persisting values

Diez B. Roggisch deets at
Mon Nov 5 20:52:58 CET 2007

Falcolas schrieb:
> Please help me understand the mechanics of the following behavior.
>>>> def d():
> 	header = 'I am in front of '
> 	def e(something):
> 		print header + something
> 	return e
>>>> f = d()
>>>> f('this')
> I am in front of this
>>>> del(d)
>>>> f('this')
> I am in front of this
> The way I understand it, function d is an object, as is e. However I
> don't quite grok the exact relationship between e and d. Is e
> considered to be a subclass of 'd', so that it has access to it's
> parent's __dict__ object, in order to access the value of 'header'? Or
> is this persistence managed in a different fashion?

The "thing" you observe here is a called a closure. It consists of the 
local variables surrounding e. So as long as you keep a reference to e, 
you keep one to the variables of d itself.


More information about the Python-list mailing list