3

我将感谢任何澄清以下内容的努力: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 的命令行参数)。

4

3 回答 3

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,)
于 2012-10-25T05:27:09.740 回答
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()
于 2012-10-25T20:30:21.913 回答
0

集合.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
于 2015-10-13T00:17:29.793 回答