Name lookup inside class definition
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Wed Jun 18 03:34:40 EDT 2008
WaterWalk a écrit :
> Hello. Consider the following two examples:
> class Test1(object):
> att1 = 1
> def func(self):
> print Test1.att1 // ok
or
print type(self).att1
> 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?
class is an executable statement. The whole "class" block is first
eval'd, then the class object is created and bound to it's name.
So when the function is called, the class statement has already been
executed, the class object created and bound to the name Test1. But when
the att2=Test2.att1 is executed, the class object doesn't yet exists,
nor the name Test2.
Anyway, you don't need to refer to the class name here:
class Toto(object):
titi = 1
toto = titi + 1
More information about the Python-list
mailing list