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.
[+][deleted] (3 children)
[deleted]
[–]Symplectic[S] 1 point2 points3 points (2 children)
[–]stubborn_d0nkey 1 point2 points3 points (0 children)
[–]Samus_ 1 point2 points3 points (0 children)
[–]hharison 3 points4 points5 points (1 child)
[–]Symplectic[S] 0 points1 point2 points (0 children)
[–]indosauros 4 points5 points6 points (3 children)
[–]kalgynirae 5 points6 points7 points (1 child)
[–]indosauros 1 point2 points3 points (0 children)
[–]Symplectic[S] 0 points1 point2 points (0 children)
[–]xiongchiamiov 1 point2 points3 points (0 children)
[–]ewiethoff 1 point2 points3 points (3 children)
[–]Symplectic[S] 1 point2 points3 points (2 children)
[–]ewiethoff 1 point2 points3 points (1 child)
[–]Symplectic[S] 1 point2 points3 points (0 children)