'self' an unknown variable???

Robin Munn rmunn at pobox.com
Mon Jan 14 10:31:15 EST 2002


On Mon, 14 Jan 2002 10:40:22 -0800, Giorgi Lekishvili <gleki at gol.ge> wrote:
>Hello all!
>
>I have written a class, with the function write. The latter is defined
>as follows:
>
>def write(self, filename, matr, cols=self.Npred, format='asc'):
>    blablabla
>    return res
>
>This doesn't work. Then I changed cols=N, previously defined
>N=self.Npred.
>Now things ar ok.
>
>Why doesn't function self.some_attr in the function declaration?

As Alex mentioned, the name "self" is not bound to anything at the time
the def statement executes. The standard way to do what you're trying to
do looks like:

def write(self, filename, matr, cols=None, format='asc'):
    if cols == None:
        cols = self.Npred
    blablabla
    return res

When you say "previously defined N=self.Npred", what does that mean? You
defined N earlier as a global? In that case, what "self" variable is it
picking up? Almost certainly not the one you intend. That way of doing
things seems very dangerous to me; you'd be much better off using None
as a default value and setting it inside your function. Or if you want
to be able to pass None as a real value for cols, use some other value
as a "default value" flag, e.g.:

def write(self, filename, matr, cols=-1, format='asc'):
    if cols == -1:
        cols = self.Npred
    blablabla
    return res

This is safe and is guaranteed to do what you intend. Doing it the other
way is asking for trouble.

-- 
Robin Munn
rmunn at pobox.com



More information about the Python-list mailing list