Creating Classes Inside A Loop Python
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: cla
Solution 1:
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'] = 5definitializer(self, x):
self.x = x + 6
d['__init__'] = initializer
MyClass = type('MyClass', (object,), d)
This produces the same class as the following class
statement.
classMyClass(object):
foo = 5def__init__(self, x):
self.x = x + 6
Post a Comment for "Creating Classes Inside A Loop Python"