简体   繁体   English

如何在 Python 中重新使用初始化的 class?

[英]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.我正在尝试从其他模块访问主应用程序中的初始化 class 但不知道该怎么做。 Background: i want to update a dataframe with data during the whole execution in the main application.背景:我想在主应用程序的整个执行过程中用数据更新 dataframe。

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:主要.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:助手.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: 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()".在主要我用“gotstats = functions.helper.GotStats()”初始化 class。 After that i can correctly use its functions and add dataframe rows by using the add function.之后我可以正确使用它的功能并通过使用添加 function 添加 dataframe 行。 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).我希望 test_function() 能够将 dataframe 行添加到同一个 object 但我不知道该怎么做(在当前代码中 test_function.py 只是创建一个新的 ZA2F2ED4F8EBC2CBB4C21A29DC4 的本地命名空间)。 Do i need to extend the class object with an function to get the active one (like logging.getLogger( name ))?我是否需要使用 function 扩展 class object 以获得活动的(如 logging.getLogger(名称))?

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:让您的test_function接受实例作为参数,并在调用它时将其传递给 function:

main.py:主要.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: 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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