Last active
August 29, 2015 14:19
-
-
Save arunpersaud/65e597b9b88c01a65f73 to your computer and use it in GitHub Desktop.
how to simplify computed attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class mytest(): | |
def init(self): | |
pass | |
def __getattr__(self, attr): | |
print("looking for ", attr) | |
print("keys: ", self.__dict__.keys()) | |
if not ("_"+attr) in self.__dict__.keys(): | |
if attr in ['a', 'b']: # would be nice to automate the next lines with a decorator on do_calc | |
self.do_calc1() | |
if attr in ['c', 'd']: | |
self.do_calc2() | |
return self.__dict__["_"+attr] | |
def do_calc1(self): | |
print("calc a, b") | |
self._a = 2 | |
self._b = 3 | |
def do_calc2(self): | |
print("calc c, d") | |
self._c = 4 | |
self._d = 5 | |
a = mytest() | |
a.a | |
a.b | |
a.c | |
a.d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment