Bob
Bob

Reputation: 415

Iteration new object instance in Python

I'm new to OOP Python I have an object:

class Object:

    def __init__(self, start_date, end_date, thing)
        self.start_date = start_date
        self.end_date = end_date 
        self.thing = thing

       ( ... ) 


    def get_things(self):
        return self.db.execute_fetchall(f"select date, p1, p2, p2, p4 from {self.thing} where date between '{self.start_date}' and '{self.end_date}'")

       ( ... ) 

Now if I have:

some_things = ["table_1", "table_2", "table_3"]
Object.get_things()

The method just selects a given table, but I want to try to be as efficient as possible. Is there any other way to poll the DB for all 3 table names other than:

for thing in things: 
    Object(start_date=start_date, end_date=end_date, thing=thing)

Should I just have this sort of logic in a bulk statement and have a get_all() method? The tables (static) I select will always be the same and I'm looking for the fastest way to select data from them...

Upvotes: 0

Views: 71

Answers (1)

kpie
kpie

Reputation: 11080

You might consider using a class variable so that you don't have to aggregate your collection of things.

class object:
    things = []
    def __init__(self, thing):
        self.thing = thing
        self.things.append(thing)
    def get_things(self):
        return(self.things)

a = object(1)
b = object(2)
c = object(3)

print(a.get_things()) # Prints [1, 2, 3]

This will likely be the fastest way as your list of things will be stored in memory and retrieving the aggregated list will not require any computation. It should be noted that this approach has its own drawbacks. For example if you change the value of some object.thing you will need to reflect that change in the list object.things as well and you will see some additional work is required for things like deletion or overriding of object instances.

Upvotes: 1

Related Questions