Python use instance of class in a function in another file

Question:

I have three files, app.py, server.py and tools.py

the files are quite big in total, so i’ll just show excerpts
server.py is basically just flask

app.py looks about like this

from server import Server
from tools import Tools

if __name__ == "__main__":
    web = Server(Server.defaultMainPage)
    tool = Tools()

    # logic

tools.py looks like this

class Tools()
    def __init__(self):

        # logic 

    def tools_func(self, args):
        # logic

server.py looks like this

from flask import Flask
from tools import Tools

class Server:

    # A lot of flask stuff, plus one function:
    def do_smth(self, args):
        # logic

        # here I want to call the tool.tools_func() function

The problem is that I create an instance of Tools in app.py. In do_smth() in server.py I want to call the tools_func() from the instance of the class I created in app.py, so tool.tools_func(). How do I that?

Asked By: Neins

||

Answers:

You can do the follwing:

  • Create a new method in app.py
  • Import this method into server.py
  • Call this method from do_smth
Answered By: Chai

Pass the tool instance as argument to do_smth function in Server.py and call tools_func like this.

def server(self, tool):
    tool.tools_func()

And in app.py you can do the following

Server.do_smth(tool)
Answered By: Vivek Singh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.