Classes and keywords

Warren Focke wfocke at phoenixdsl.com
Mon Sep 18 17:50:11 EDT 2000


Michael Husmann:
> class Foo:
>     def __init__(self):
>         self.k = 0
> 
>     def set(self, w=self.k):
>         return w * w

The "def set..." statement is executed at module load time, and the
default value for w is evaluated then.  It is evaluated with the body of
the class as its local scope.  The only symbols in the local namespace
at that time are __init__ and set, and the only one in the global
namespace is sys (and a few magical implementation details).  The only
places that self appears are in the body of the methods, so the symbol
is undefined until one of those methods is called.  But that never
happens, because the interpreter choked on the undefined symbol self
when trying to create the class.

My way out would probably be

    def set(self, w=None):
        if w is None:
            w = self.k
        return w * w

Warren Focke
-- 
Just because romance and rapture have so often served as a pretext for
curdled banality doesn't make the sentiments themselves obsolete.
 -- Michelle Goldberg



More information about the Python-list mailing list