Anish Sinha
Anish Sinha

Reputation: 305

How can I run one method of a class automatically, before any other class methods in Python, when a new class instance is created

Question says it all: I have a class in python which has several methods, and I want one of them to be run before any of the other functions in the class. I want to store the result of this calculation in a variable called cache, so I can save the data and minimize function calling for optimization purposes. What is the best way to accomplish this? Example code is listed below:

class Foo: 
    def __init__(self, bar):
        self.bar = bar
        self.cache = []

    def baz(self):
        #do some calculation
        #store it in the cache
        self.cache.append(<result of calculation>)
        return 0
    
    def qux(self):
        # this function requires the output of baz in the cache
        # How can I automatically have this class run the baz method before any other method of the class so that I can utilize the cache?
        return 0 

As always, if you take the time to answer or attempt to answer this question, thank you for your time.

Upvotes: 0

Views: 1697

Answers (1)

Alan
Alan

Reputation: 3042

If baz is always going to be needed in every circumstance, put it in __init__.

If baz is always going to be needed for qux, put a call to baz in qux with a test.

In __init__:

def __init__(self, bar):
    self.bar = bar
    self.cache = []
    self.baz()

In baz:

def qux(self):
    try:
        self.calculation(self.cache)
    except:
        self.baz()
        self.calculation(self.cache)

where your calculations are being carried out in calculation(self, cache_set) which should raise an exception if no cache is present.

Upvotes: 1

Related Questions