Classes and keywords

Carel Fellinger cfelling at iae.nl
Mon Sep 18 23:46:33 CEST 2000


Michael Husmann <Michael.Husmann at t-online.de> wrote:
> The following code is refused by python and I wonder why:

this is a tricky one, no doubt others will provide you with better
explanations, but I give it a try...

> class Foo:
>     def __init__(self):
>         self.k = 0

>     def set(self, w=self.k):

here self.k is looked up in the 'enclosing scope', that is the class Foo
scope, *not* in the scope of an instantiation of that class!  And within
that class scope there is no self. You could create one with an assignment
statement at the same level as the def statements, but that would be a
different self then the selfs used in those functions, without its
magical behaviour of refering to an instance of that class, unless...

Let me try to explain with a few examples:


### we start of with the class statement, creating the class scope
class C:

    ### within this class scope we create a var
    ### (this statement is executed right away)
    class_var = 1

    def __init__(self):
        ### here we create a var at the instance level
        ### but we only do that at class instantiation, like "c=C()"
        self.instance_var = 2

    ### within this class scope we create a function with the def statement
    ### mind you self and v are only known inside this function, but
    ### class_var is known in the current class scope
    def fun(self, v=class_var):
	return v*v

    def more_fun(self, v=None):
        if v == None:
             ### mind you that the `instance' scope is out of order here,
             ### but fortunately reachable through this magical first
             ### parameter normally called self
             v = self.instance_var
        return v*v


There are more tricks to learn...

e.g when in the __init__ function, or anywhere else you would assign to
class_var, then despite its name it would turn into an instance_var and
hide away the true class_var in references like "self.class_var". Lukily
you still can get to the true class_var using "C.class_var".

There, how is that for creating confusion.
-- 
groetjes, carel



More information about the Python-list mailing list