0

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.

Ben
  • 51,770
  • 36
  • 127
  • 149
FrigidDev
  • 222
  • 1
  • 2
  • 13
  • The fact that you find yourself needing to do this suggests that your approach could be improved. What is the bigger picture; why are you doing this, what are you trying to achieve? – jonrsharpe Apr 26 '14 at 07:23
  • Hi, and welcome to Stack Overflow - there's no need to add solved to your question. By clicking the checkmark you've already indicated to the wider community that you've got the answer you need. Thanks! – Ben Apr 26 '14 at 15:01
  • @Ben, sorry, I'm just used to that from using the Ubuntu forums, my bad. :) – FrigidDev Apr 27 '14 at 01:01

1 Answers1

2

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.

Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143
  • So, from what I've read, I need to put the name, type(such as object), and the different attributes in a dictionary like this: {"self.var: var}. – FrigidDev Apr 26 '14 at 07:11