JMFilipe
JMFilipe

Reputation: 23

Sharing data between class objects

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?

Upvotes: 0

Views: 2983

Answers (1)

Stop harming Monica
Stop harming Monica

Reputation: 12590

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)

Upvotes: 2

Related Questions