Suppose I have the following code:
import pandas as pd
import cx_Oracle
class Foo:
instances = []
def __init__(self, id, name):
self.id = id
self.name = name
dsn_tns = cx_Oracle.makedsn('***', '***', service_name='***')
conn = cx_Oracle.connect(user=r'***', password='***', dsn=***)
self.data = pd.read_sql(***, conn)
conn.close()
Foo.instances.append(self)
def method1(...):
...
def method2(...):
...
one = Foo(1, 'one')
Where I create a class and initialize one (or potenitally more) instances of that class.
In this case I am importing some data from an oracle server which takes a long time for the SQL query to run.
Say I run method1 on my object:
one.method1...
after running this say I decide I want to use method2 on one:
one.method2...
Now I will have to run the code again which will have to reinitialize one as an instance of the class Foo, which will force the SQL query to rerun which takes time. It will also rerun method1 on one which may also take a long time.
I am a beginner so I am wondering what is the best way around this?
Something like storing one in memory so when I rerun the code it doesn't have to initialize one again and applies the method directly to the object in memory?
Also is there a way to store potential outputs of method1 so when I run
one.method1
one.method2
It doesn't have to re-do one.method1 if it has been run previously.
Obviously this is not a problem on things that run fast but on code with many methods and many objects in a class and many classes etc. I can imagine this would become overwhelming.
I am sure a solution and best practices do exist but I am struggling to find help on this issue.
I suspect this is a general thing with all OOP and not just python.
Thank you.