简体   繁体   中英

How can i re-use an initialized class in Python?

I'm trying to access a initialized class in the main application from other modules but don't know how to do it. Background: i want to update a dataframe with data during the whole execution in the main application.

I have to following application structure (this is an simplified version of the code in my application):

constraints
- test_function.py (separate module which should be able to update the initialized class in the main app)
functions
- helper.py (the class which contains the dataframe logic)
main.py (my main application code)

main.py:

import functions.helper
gotstats = functions.helper.GotStats()

gotstats.add(solver_stat='This is a test')
gotstats.add(type='This is a test Type!')

print(gotstats.result())

import constraints.test_function
constraints.test_function.test_function()

helper.py:

class GotStats(object):
    def __init__(self):
        print('init() called')
        import pandas as pd
        self.df_got_statistieken = pd.DataFrame(columns=['SOLVER_STAT','TYPE','WAARDE','WAARDE_TEKST','LOWER_BOUND','UPPER_BOUND','OPTIMALISATIE_ID','GUROBI_ID'])

    def add(self,solver_stat=None,type=None,waarde=None,waarde_tekst=None,lower_bound=None,upper_bound=None,optimalisatie_id=None,gurobi_id=None):
        print('add() called')
        self.df_got_statistieken = self.df_got_statistieken.append({'SOLVER_STAT': solver_stat,'TYPE': type, 'WAARDE': waarde, 'OPTIMALISATIE_ID': optimalisatie_id, 'GUROBI_ID': gurobi_id}, ignore_index=True)

    def result(self):
        print('result() called')
        df_got_statistieken = self.df_got_statistieken
        return df_got_statistieken

test_function.py:

import sys, os
sys.path.append(os.getcwd())

def test_function():
    import functions.helper
    gotstats = functions.helper.GotStats()
    gotstats.add(solver_stat='This is a test from the seperate module')
    gotstats.add(type='This is a test type from the seperate module!')
    print(gotstats.result())

if __name__ == "__main__":
    test_function()

In main i initialize the class with "gotstats = functions.helper.GotStats()". After that i can correctly use its functions and add dataframe rows by using the add function. I would like that test_function() is able to add dataframe rows to that same object but i don't know how to do this (in current code the test_function.py just creates a new class in it's local namespace which i don't want). Do i need to extend the class object with an function to get the active one (like logging.getLogger( name ))?

Any help in the right direction would be appreciated.

Make your test_function accept the instance as a parameter and pass it to the function when you call it:

main.py:

import functions.helper
from constraints.test_function import test_function


gotstats = functions.helper.GotStats()
gotstats.add(solver_stat='This is a test')
gotstats.add(type='This is a test Type!')

print(gotstats.result())

test_function(gotstats)

test_function.py:

import sys, os
import functions.helper

sys.path.append(os.getcwd())


def test_function(gotstats=None):
    if gotstats is None:
        gotstats = functions.helper.GotStats()

    gotstats.add(solver_stat='This is a test from the seperate module')
    gotstats.add(type='This is a test type from the seperate module!')
    print(gotstats.result())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM