A newbie in more need....

Bengt Richter bokr at oz.net
Sat Oct 2 00:57:26 EDT 2004


On Fri, 01 Oct 2004 08:55:15 -0400, Peter L Hansen <peter at engcorp.com> wrote:

>Chris Patton wrote:
>> I am writing a program that writes a number of classes, which are all
>> fundementally the same thing. The only thing that is different is the
>> names. Therefore, I need to write a bunch of classes in the quickest
>> time I can. Here's what I was thinking of:
Why didn't you _try_ your own code, Chris? It wouldn't have taken any more typing ;-)

>> 
>> num = 1
>> while num < 20:
>>       exec 'class bug'+num+':'
>>       exec '      gender = "m"'
>>       exec '      size = 0'
>>       exec '      skill = 0'
>> 
>> Obviously, the "exec" statement severley slows the time it takes to
>> write these classes. I need a new method! If possible I would like to
>> avoid the use of the "exec" statement alltogether.
I guess you did avoid it, since otherwise you would at least have discovered

 >>> num = 1
 >>> while num < 20:
 ...     exec 'class bug'+num+':'
 ...     exec '      gender = "m"'
 ...     exec '      size = 0'
 ...     exec '      skill = 0'
 ...
 Traceback (most recent call last):
   File "<stdin>", line 2, in ?
 TypeError: cannot concatenate 'str' and 'int' objects

-- for starters. If you don't do your part, you can expect people to lose interest
in helping you. Another pointer: If you are new to town, you can ask an old taxi driver
how certain streets connect, and he can answer, but if you have an address to go to, tell
him that. You'll generally get there faster ;-)

>
>for i in range(1, 20):
>     class _proto:
>         gender = "m"
>         size = 0
>         skill = 0
>
>     globals()['bug%s' % i] = _proto
>
>This does almost exactly what you want, and for most
>intents and purposes is the same thing.  (The encoded
>name of the class is different, but that shouldn't
>be relevant to you in most cases.)
>
If it is, type is handy:

 >>> for i in xrange(1,10):
 ...     name = 'bug%s'%i
 ...     globals()[name]=type(name,(),dict(gender='m', size=0, skill=0))
 ...

Have a look at one
 >>> bug7
 <class '__main__.bug7'>
 >>> bug7.gender, bug7.size, bug7.skill
 ('m', 0, 0)

>The real question has already been asked by others,
>however:  what's the point of auto-generating names for
>things when nothing will be able to refer to them without
>knowing their names in advance anyway?
Well, I guess there could be reasons, but guessing gets old sometimes ;-/

Regards,
Bengt Richter



More information about the Python-list mailing list