Question

I need to name classes certain things, for example:

for a in range(10):
    class Class#"%s"(object): % (num)
         '''Class Content'''
    num += 1

My question, is this possible, and if not, what is an alternative.

Was it helpful?

Solution

You can do it using metaclasses (stuff that is used to create classes). Example:

>>> type('ClassName', (), {})
<class '__main__.ClassName'>

Second argument is a tuple of base classes, third argument is a dictionary containing attribute name -> attribute value pairs:

>>> cls = type('ClassName', (object,), {'varname': 'var'})
>>> cls.varname
'var'

From the documentation on type function:

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute.


Also read this awesome answer for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top