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.

3
  • 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? Commented Apr 26, 2014 at 7: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! Commented Apr 26, 2014 at 15:01
  • @Ben, sorry, I'm just used to that from using the Ubuntu forums, my bad. :) Commented Apr 27, 2014 at 1:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.