pretty basic instantiation question

Steve Holden steve at holdenweb.com
Mon Oct 23 20:06:05 EDT 2006


Leif K-Brooks wrote:
> sittner at lkb.ens.fr wrote:
> 
>>let's say i have a class, and i need to create a different number of
>>instances (changes every time - and i can't know the number in advance) in
>>a loop.
>>a function receives the number of instances that are needed, and creates
>>them like,
>>a=Myclass()
>>b=Myclass()
> 
> 
> def create_instances(n):
>      return [Myclass() for i in xrange(n)]

Leif's point being you *don't* want to bind a different name to each of 
a variable number of things - that way madness lies, as you end up 
creating Python statements on the fly using eval() and exec and other 
such dangerous and insanity-inducing tricks :-)

Instead use a container structure like a list to hold them, and then use 
an appropriate technique to access them while they are still in the 
container.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list