By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,760 Members | 1,091 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,760 IT Pros & Developers. It's quick & easy.

Name lookup inside class definition

P: n/a
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.
Jun 27 '08 #1
Share this Question
Share on Google+
3 Replies

P: n/a
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
Jun 27 '08 #2

P: n/a
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
Jun 27 '08 #3

P: n/a
Ah, I see. Thank you all.
Jun 27 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.