Creating classes inside a loop Python

北慕城南 提交于 2020-07-23 10:34:46

问题


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!


回答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'] = 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


来源:https://stackoverflow.com/questions/27697285/creating-classes-inside-a-loop-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!