Class Encapsulation Errors in Python 2.3.3

Carlos Ribeiro carribeiro at gmail.com
Fri Nov 19 10:43:10 EST 2004


On 19 Nov 2004 10:44:56 GMT, Duncan Booth <duncan.booth at invalid.invalid> wrote:
> Jeff Shannon wrote:
> 
> > The problem here is that default values in functions/methods are
> > evaluated at *compile* time.
> 
> Actually, no. The default values in functions/methods are evaluated when
> the def statement is *executed* not when anything is compiled. If you
> execute the def multiple times the default values are recalculated each
> time.

Be careful :-) default values are calculated when the def statement is
executed.... which is not the same as to say that they are calculated
every time the function is called.

To explain it better. In a conventional Python program, the def
statement is executed only once, when a module is loaded, for example.
In this case, default values are stored as attributes of the function
object. In this case, the value of the default never changes.

*If* for some reason your code runs over the def statement multiple
times, *then* a new function object will be created with new default
values. For example, this can happen if you force-reload a module, or
def the function inside a for loop (weird but it works):

for i in (1,2,3):
    def print_i(x=i):
         print x,i

>>> print_i()
3 3
>>> i = 0
>>> print_i()
3 0

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list