0

I'm working on a Python project and I want to do something like the next example, but is incorrect. I need some help, please!

names = ['name1', 'name2']

for name in names:
    class name:
        [statements]

Thank you!

  • Explain what you are trying to accomplish, and in what way this is "incorrect". – Scott Hunter Dec 29 '14 at 23:05
  • Related: [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) and [How do you create different variable names while in a loop? (Python)](http://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop-python) – Ashwini Chaudhary Dec 29 '14 at 23:13

1 Answers1

10

The class statement requires a hard-coded class name. You can use the type function, however, to create such dynamic classes.

names = ['name1', 'name2']
class_dict = {}
for name in names:
    # statements to prepare d
    class_dict[name] = type(name, (object,), d)

Here, d is a dictionary that should contain any attributes and methods that you would have defined in your class. class_dict is used to store your class objects, as injecting dynamic names directly into the global namespace is a bad idea.

Here is a concrete example of using the type function to create a class.

d = {}
d['foo'] = 5
def initializer(self, x):
    self.x = x + 6
d['__init__'] = initializer
MyClass = type('MyClass', (object,), d)

This produces the same class as the following class statement.

class MyClass(object):
    foo = 5
    def __init__(self, x):
        self.x = x + 6
chepner
  • 497,756
  • 71
  • 530
  • 681
  • As `type()` creates an object of `` (not `classobj`) we can replace `(object,)` with `()`. But yeah *Explicit is better than implicit.* :-) – Ashwini Chaudhary Dec 29 '14 at 23:16
  • Ah, true, I see a `type` instance inherits from `object` whether or not you include `object` in the base-class tuple. – chepner Dec 30 '14 at 00:45