Home > Blockchain >  python simple OOP for passing args and decorator
python simple OOP for passing args and decorator

Time:09-01

I'm new to OOP, I'm trying to create a class and function that receives names and create the SQL calls for me, like: df_1 and df_2.
However I want that my class manages it for me, so the args will be just to repeat the names, like: ('table1', 'table2', 'n'..)..

So how can I do this in the best way? As I'm learning I appreciate explanations

import pandas as pd
from def_funcs import sup  # I got my data base engine from this func
from typing import Tuple, List, Dict

# NON OOP WAY
df_1 = pd.read_sql("""
    select * from table1
    """, sup.start_engine())
print(df_1.columns)

df_2 = pd.read_sql("""
    select * from table2
    """, sup.start_engine())
print(df_2.columns)

OOP WAY << EXPECTED >>

class ExtractDb:
def __init__(self, tbl_name, tables):
    self.tbl_name = tbl_name
    self.get_tables = tables

def get_tables(*args: str) -> Tuple[str]:
    return args

def create_db(self, tbl):
    tbl = self.tbl_name
    tbl = pd.read_sql(self.get_tables, sup.start_engine())
    return tbl
    # print(ExtractDb.get_tables('', '2', '3', '4'))
    print(ExtractDb.create_db())

The output will be the number of tables passed as args within tuples or dict (whatever).

Maybe my code is really messed up, feel free to modify it!!

CodePudding user response:

You can try these two approaches:

  1. Use a simple function
import pandas as pd
from def_funcs import sup  # I got my data base engine from this func
from typing import Tuple, List, Dict

def get_dataframes(tables):
    dataframes = []
    for t in tables:
        sql = f"SELECT * FROM {t}"
        dataframe = pd.read_sql(sql, sup.start_engine())
        dataframes.append(dataframe)
    return dataframes
  1. Use the OOP approach
class ExtractDb:

    def __init__(self, tables):
        self.tables= tables

    def get_tables(*args: str) -> Tuple[str]:
        return args

    def create_db(self, tbl):
        dataframes = []
        for t in self.tables:
            sql = f"SELECT * FROM {t}"
            dataframe = pd.read_sql(sql, sup.start_engine())
            dataframes.append(dataframe)
        return dataframes
  • Related