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!
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!
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