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!

2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

As type() creates an object of <type 'type'> (not classobj) we can replace (object,) with (). But yeah Explicit is better than implicit. :-)
Ah, true, I see a type instance inherits from object whether or not you include object in the base-class tuple.

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.