[Tutor] List of class instances

Kent Johnson kent37 at tds.net
Tue Sep 20 11:59:45 CEST 2005


Jan Eden wrote:
>>I'd like to form a list of class instances. The following does not work 
>>(TextfieldLong, Textarea, TextfieldShort etc being class names):
>>
>>   fields = [
>>       TextfieldLong(name='title', label='Seitentitel', value=''),
>>       Textarea(name='content', label='Inhalt', value=''),
>>       ShortField(name='mother_id', label='MotherID', value=1)
>>   ]
>>   
> 
> 
> Just found that it *does* work, but that I have to define the classes above the list assignment. Why is that? Why would Python not find the classes within the same file?

Class definitions are executable statements that bind the name of the class to a class object. Before the definition is executed the class is undefined, like any other assignment. For example you wouldn't expect this to work:

values = [x, y, z]
x=1
y=2
z=3

Your code suffers from the same problem. When you say
class foo:
  pass

this means, roughly,
foo = (the result of executing the class body)
and the name 'foo' is not defined until this executes.

Kent



More information about the Tutor mailing list