Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making HTTP request upon class initialization

Tags:

python

New to programming, so may be a stupid question. If so, apologies.

I'm writing a class in Python that on initialization makes a get request to an API for a rather large amount of data:

class Foo:
    def __init__(self, params):
        self.params = json.dumps(params)
        self.r = requests.get(api, data=self.params).json()

After initialization, there are a bunch of methods — bar and baz — that are all meant, in my ideal world, to perform different operations on the the JSON that is fetched upon initialization.

When I instantiate the class and call the methods in succession, I do something like this:

test = Foo()
test.bar()
test.baz()

My naive understanding is that test.bar() and test.baz() are performing operations on the same JSON fetched upon instantiation of test and are not making their own API calls. Obviously, the whole thing would be much slower if test.bar() and test.baz() are each making their own requests. Is my understanding correct? Or are test.bar() and test.baz() fetching their own copies of the JSON data?

like image 934
user139014 Avatar asked Jul 05 '26 06:07

user139014


1 Answers

It entirely depends on the content of the bar and baz functions. They could call requests.get if that's how you write them.

If you're wondering whether or not the __init__ function is called when you call test.bar(), the answer is no, it is not. __init__ is only called when you instantiate a Foo object.

like image 120
Brionius Avatar answered Jul 06 '26 21:07

Brionius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!