On Tue, 17 Jun 2008 23:05:56 -0700, WaterWalk wrote: > Hello. Consider the following two examples: class Test1(object): > att1 = 1 > def func(self): > print Test1.att1 // ok > > class Test2(object): > att1 = 1 > att2 = Test2.att1 // NameError: Name Test2 is not defined > > It seems a little strange. Why a class name can be used in a method > while cannot be used in the class block itself? I read the "Python > Reference Manual"(4.1 Naming and binding ), but didn't get a clue.
It's because functions actually defer the name lookup. So you can use *any* name in a function, basically. If it's there at the function's runtime (not its declaration time), you're okay. During the execution of a class body, the class is not yet created. So you're running this ``Test2.att1`` lookup already (it has to be executed *now*, during the class creation) and fail because the class is not there. You can still refer to the class' scope as a local scope:: >>> class A(object): ... att1 = 1 ... att2 = att1 + 2 ... >>> A.att1 1 >>> A.att2 3 HTH, -- Robert "Stargaming" Lehmann -- http://mail.python.org/mailman/listinfo/python-list