如何从列表动态生成类? [英] How do you dynamically generate classes from a list?

查看:61
本文介绍了如何从列表动态生成类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,该类会自动为以后可以访问的值添加一个持有人,以便当我运行cd.orders或cd.users时,它将返回或为我刚刚提供的每个表提供一个数据框

I want to create a class that automatically adds a holder for values that I can access in the future so that when I run cd.orders or cd.users it will return or give me a dataframe of each of the tables I just queried against.

这里是我的示例代码:

class samplecode:
    def __init__(self,credentials):
        c = credentials ('DATABASE', 'USER', 'PASSWORD', 'HOST', 'PORT', 'SCHEMA')
        print('credentials loaded')
        self.connection_string = "postgresql://%s:%s@%s:%s/%s" % (c.USER,
                                                                  c.PASSWORD,
                                                                  c.HOST,
                                                                  str(c.PORT),
                                                                  c.DATABASE)
        self.engine = sa.create_engine(connection_string)
        print('redshift connected')
        self.data = []

    def get_db(self,tables):
        for t in tables:
            self.data = pd.read_sql_query('SELECT * FROM database.{} limit 10'.format(t),engine)
            print(self.data.head(2))

cd = samplecode(credential)
# llf.view_obj
cd.get_db(['orders','user'])

我希望是在cd.get_db之后,它将返回或给我两个实例/对象。当我键入dir(cd)

What I am hoping is that after cd.get_db it will return or give me two instances/objects. When I type dir(cd)

我应该能够执行cd.orders和cd.user,并且如果我在列表cd.xyz中添加更多内容。

i should be able to do cd.orders and cd.user and if I add more to the list cd.xyz.

我尝试了此操作,但只能访问最新的df,因为它会覆盖另一个df

I tried this but could only access the most recent df since it overwrites the other df

class Wrapper(object):
    def __init__(self, data):
        self.data = data
    def __getattr__(self, attr):
        return [d[attr] for d in self.data]

# Wrapper([{'x': 23}, {'x': 42}, {'x': 5}]) 
instancelist = ['orders','user']

for i in instancelist:
    data = Wrapper([{i:'a'}])
cd.data

Hopnig对此事提供了帮助和澄清!

Hopnig for help and clarification on the matter thanks!

否则,请考虑以下事项:

or if this is confusing, consider the following:

class BaseClass:
    def __init__(self):
        self.a = []
        self.b = []

    def execute_query(self,table_name):
        for tables in table_name:
            self.table_name = run_query()

table_list = ['D','E','F']
test = BaseClass
test.execute_query(table_list)

dir(test)
[
 'a',
 'b',
 'D',
 'E',
 'F'
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
]


推荐答案

听起来您正在寻找 setattr 内置的。您可以调用它以将属性(以字符串形式)分配给对象。因此,不必打印表,您可以将每个表分配给以表名称命名的属性:

It sounds like you're looking for the setattr builtin. You can call it to assign an attribute (given as a string), to an object. So rather than printing out your tables, you can assign each one to an attribute named after the table's name:

def get_db(self,tables):
    for t in tables:
        data = pd.read_sql_query('SELECT * FROM database.{} limit 10'.format(t), engine))
        setattr(self, t, data)

您还可以朝另一个方向做事,并查找属性触发数据库查询。为此,您想向您的课程添加 __ getattr __ 方法。

You could also do things in the other direction, and have the lookup of an attribute trigger a database query. For that you'd want to add a __getattr__ method to your class. That would be called when an attribute was looked up and not found normally.

def __getattr__(self, name):
    data = pd.read_sql_query('SELECT * FROM database.{} limit 10'.format(name), engine))
    setattr(self, name, data)  # save to an attribute so we don't need to query it again
    return data

这篇关于如何从列表动态生成类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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