How to set instance variable only when first called upon
I'm working with Python/Sage, and running into some performance issues. Suppose I want to set up an instance variable as follows:
class MyClass:
def __init__(self):
self.x1 = factorial(10^7)
Now, obviously, my computer is going to take a bit of time to calculate that factorial. I'd rather it not run that computation every time I construct an instance, and only do it when I call upon that particular variable. One solution I've come across is this:
class MyClass:
def x2(self):
try:
return self.x1
except AttributeError:
self.x1 = factorial(10^7)
return self.x1
But this just seems so messy, and requires more variable/method names. Is there some way to say to Python, "Hey, look, I need you to set this instance variable, but can you wait until I actually need it first?" I'm only using factorial(10^7) as an example.
Posted Sep 4, 2014, 2:46 AM UTC
[deleted]
This is exactly what I need. Thank you so much!
Edit: Oh dang, I didn't know that about sage. That cache method would have been ideal. Thank you, though.
http://ideone.com/Hyy3TJ
That's my shitty replication. It's missing the ability to use any number of arguments, sorry I'm currently on mobile, if you need that and cant figure out how by yourself let me know and I'll get to adding that when I can (warning: dict keys have to be hashable)
how about this?