A newbie in more need....

Robert Brewer fumanchu at amor.org
Fri Oct 1 06:57:02 CEST 2004

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:
> 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.

import types

for x in xrange(20):
    n = 'bug%s' % x
    globals()[n] = types.ClassType(n, (object,),
                                   {'gender': 'm', 'size': 0,
                                    'skill': 0})

del n
del x


>>> import classtest
>>> dir(classtest)
['__builtins__', '__doc__', '__file__', '__name__', 'bug0', 'bug1',
'bug10', 'bug11', 'bug12', 'bug13', 'bug14', 'bug15', 'bug16', 'bug17',
'bug18', 'bug19', 'bug2', 'bug3', 'bug4', 'bug5', 'bug6', 'bug7',
'bug8', 'bug9', 'types']
>>> dir(classtest.bug8)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__',
'gender', 'size', 'skill']
>>> classtest.bug8.gender

Robert Brewer
Amor Ministries
fumanchu at amor.org

More information about the Python-list mailing list