0

I do mostly scientific related programming, which usually ends being very sequential. I'm trying to improve my coding skills and use OOP when I need to replicate similar structures or when passing many parameters through functions. So far I've being doing fine but lately I found a problem.

Imagine a chunk of information that I get by executing a query to a SQL database. Then I want to have these values in memory (to avoid multiple querys) and share them with different objects of a class.

I tried something like this:

Class Data:
    def __init__(self, query):
        self.df = read_sql(query)

Class Object(Data):
    def __init__(self, params):
        super().__init__()
        # some processes with params 
    def methods():
        # some methods which uses values from Class Data

But every time that an Object() is created calls Data and the query is executed. Is there any way to share the data without passing it as an argument?

Maybe Class Object inside Data?

5
  • 1
    What if different queries are used? Are you saying you want to cache calls or operate at a class level instead of an instance? Commented Mar 6, 2016 at 17:39
  • 1
    If you want to keep the chance to pass in the query per instance you should cache the result of the query and the query itself at the class level then check if it is in the cache before you run the query, otherwise why take a query parameter at all? Commented Mar 6, 2016 at 17:45
  • @PadraicCunningham I have similar data structures which require different querys, hence the parameter. How can I cache the results of the query? Commented Mar 6, 2016 at 17:51
  • 1
    At a very basic level use a dict as a class attribute and store the query as the key and the return as a value. You could also implement an lru cache docs.python.org/3/library/functools.html#functools.lru_cache which would allow you to set a size limit Commented Mar 6, 2016 at 17:52
  • 1
    Thanks, I'll give it a try. Commented Mar 6, 2016 at 17:59

1 Answer 1

2

What you are doing is not sharing but subclassing. If you want to reuse the same instance of Data with several instances of Object then this might make sense:

Class Data:
    def __init__(self, query):
        self.df = read_sql(query)

Class Object:
    def __init__(self, data, params):
        self.data = data
        # some processes with params

    def methods():
        # some methods which uses values from Class Data

This is how you'd use these classes:

data = Data(query)
obj1 = Object(data, params1)
obj2 = Object(data, params2)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.