Nate Stemen Nate Stemen - 1 year ago 43
Python Question

Initialize variable if class method is run

I have a class, like

class D:
def __init__(self):
"""some variables"""
def foo(self):
"""generates lots of data"""


I would like to be able to store all of the data that
foo
creates within the instance of the class that
foo
is being called from. Almost like creating a new initialization variable, but only once the method is called. For if the user never calls
foo
, no need to have generated the data to begin with.

Thanks!

Answer Source

How about to make a flag which will say if data was already generated?

class D:
    def __init__(self):
        self.already_generated = False
        """some variables"""
    def foo(self):
        """generates lots of data"""
        if not already_generated:
            self.generate()...
            already_generated = True

    def generate(self,...):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download