动态创建Python中的几个类

时间:2012-10-24 23:27:02

标签: python oop

我将非常感谢澄清以下内容:Python中是否有一种方法可以为每个类动态创建一个对象,其中声明了几个类?我的愚蠢猜测可以描述如下:

...

假设我们有来自db

的一些数据
props = dict_cur.fetchall() 
classes_names = []
data = []

for i in props:
    classes_names.append(i['client_name'].title()) 

classes = []
data = []

for i in props:
    data.append(dict(i)) 

for i, d in zip(classes_names, data):
    classes.append(type(i, (object,), dict(**d)))

print classes
#printing list of classes

objects = []
for obj in classes:
objects.append(obj())

for obj in objects:
    print obj.client_name, obj.client_id

这是一种非常天真的方法,它永远不会以常规方式从已创建的类继承,就像这样:

class ClientProcess(Someclient): #Someclient is the name of the created class before


    def __init__(self):
        print "Someclient stuff" 

目标非常简单:创建几个类的对象,最好使用存储在表中的属性,但同时为每个客户端都有类声明,这些客户端将实现从类到非常类的特定方法类。运行良好且使用Python版本的Factory方法的初始脚本是不够的,因为它只能处理一个类(客户端)一次(基于命令行参数,即客户端ID)。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以使用以下方法为动态创建的类创建子类:

In : classes = []

In : cls_name = 'BaseCls1'

In : classes.append(type(cls_name, (object, ), {'x': 1}))

In : classes[0].x
Out: 1

In : classes[0].__bases__
Out: (object,)

# two ways to create subclass out of BaseCls1

In : class SubCls1(classes[0]):
   :     x = 2
   :
In : SubCls1.x
Out: 2

In : SubCls1.__bases__
Out: (__main__.BaseCls1,)


In : SubCls2 = type('SubCls2', (classes[0],), {'x': 2})

In : SubCls2.x
Out: 2

In : SubCls2.__bases__
Out: (__main__.BaseCls1,)

答案 1 :(得分:0)

class GetConfig(object):

    def __init__(self, client_id):
        self.client_id = client_id
        #construct the query here to get the clients data ...where client_id = self.client_id
        d = {'logfile': 'some_long_path', 'contact_name': 'some_name'}


    class FirstClient(object):

    def __init__(self):
        client_id = '111111111'
        props = GetConfig(client_id)
        #print props.d

    def check_source(self):
        print "Checking FirstClient source"
        return "Something"
        #print props.d

    def check_downl(self):
        print "Checking FirstClient downloaded"


class SecondClient(object):

    def __init__(self):
        client_id = "222222"
        props = GetConfig(client_id)


    def check_source(self):
        print "Checking SecondClient source"

    def check_downl(self):         
        print "Checking SecondClient downloaded"

myfactory = {
"firstclient" : FirstClient,
"secondclient" : SecondClient,
}

for i in myfactory.values():

    i().check_source()
    i().check_downl()

答案 2 :(得分:0)

collections.namedtuple。完成。 编辑:详细说明,

from collections import namedtuple
rows = dict_cur.fetchall() 
# creates the class Row which is a tuple, but each position argument
# corresponds to the column name in that position
# Row can be instantiated as a tuple and then its elements can be accessed
# by name class attributes 
Row = namedtuple("Row", zip(*dict_cur.description)[0])
objects = [Row(row) for row in rows]

for o in objects:
     print o.client_name, ' is ' , o