在循环Python中创建类 [英] Creating classes inside a loop Python

查看:96
本文介绍了在循环Python中创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个Python项目,我想做类似下一个示例的操作,但是不正确。我需要一些帮助!

  names = ['name1','name2'] 

名称中的名称:
类名:
[声明]

谢谢!

解决方案

class 语句需要一个硬编码的类名。但是,可以使用 type 函数来创建此类动态类。

  names = ['name1','name2'] 
class_dict = {}
用于命名名称:
#准备d的语句
class_dict [name] = type(名称(对象)d)

此处, d 是一个字典,其中应包含您将在类中定义的所有属性和方法。 class_dict 用于存储您的 class 对象,因为将动态名称直接注入全局命名空间是一个坏主意。 / p>

以下是使用 type 函数创建类的具体示例。

  d = {} 
d ['foo'] = 5
def初始值设定项(self,x):
self.x = x + 6
d ['__ init__'] =初始值设定项
MyClass = type('MyClass',(object,),d)

这将产生与以下 class 语句相同的类。

  class MyClass(object):
foo = 5
def __init __(self,x):
self.x = x + 6


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

这篇关于在循环Python中创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆