0

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!

1
  • 1
    Well, you can bind new attributes to the instance in form of the generated data in foo when the method is called the first time, and avoid those in subsequent calls by setting say a flag attribute. Commented Jul 25, 2017 at 16:13

2 Answers 2

2

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,...):
Sign up to request clarification or add additional context in comments.

1 Comment

your comment made me think, I could just do self.data = None, and then just check to see if it is None and set it to the data when that function is called. Good idea!
0

Not quite sure if this is what you're trying to do, but if you want a class method to generate data that can be accessed from that instance you can put it into a data structure that is a member of that class:

class D:
    def __init__(self):
        #class member variables here
        self.fooArray = []
    def foo(self):
        #insert your data to self.fooArray here, eg:
        for i in range(1, 10000):
            self.fooArray.append(i)

1 Comment

You probably want self.fooArray when you make it

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.