Classes and keywords

Quinn Dunkan quinn at mark.ugcs.caltech.edu
Tue Sep 19 00:50:33 EDT 2000


On Mon, 18 Sep 2000 20:51:34 +0200, Michael Husmann
<Michael.Husmann at t-online.de> 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

The 'def' statements are executed when the class is executed.  'self' is bound
when the method of a class instance is called.  So at the time
'def set(...)' is executed, there is no self.  Remember, default arguments are
executed at compile time, not at run time.  This trips people, which is why
'def foo(arg=[])' is a faq item.

>Is there someone who can help me using such a keyword argument like I
>have done in that 'set' function.

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



More information about the Python-list mailing list