Classes and keywords

Michael Husmann Michael.Husmann at t-online.de
Mon Sep 18 15:21:03 EDT 2000


Thank you Bjorn. 

I have found that too. I assumed that the constructor function
(__init__) would have made that variable public for the class.
I think this kind of workaround is not very elegant, but I fear there is
no other way.

Michael

Bjorn Pettersen wrote:
> 
> The problem you're seeing is that self (in the set method) is not
> defined until you get to the method _body_. A possible workaround is:
> 
>   def set(self, w=None):
>       if w is None:
>           w = self.k
>       return w * w
> 
> -- bjorn
> 
> Michael Husmann wrote:
> >
> > The following code is refused by python and I wonder why:
> >
> > import sys
> >
> > class Foo:
> >     def __init__(self):
> >         self.k = 0
> >
> >     def set(self, w=self.k):
> >         return w * w
> >
> > def main():
> >     k = Foo()
> >     print k.set(9)
> >
> > if __name__ == "__main__": main()
> >
> > Traceback (most recent call last):
> >   File "<stdin>", line 11, in ?
> >   File "<stdin>", line 15, in Foo
> > NameError: There is no variable named 'self'
> >
> > Is there someone who can help me using such a keyword argument like I
> > have done in that 'set' function.
> > --
> > http://www.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list