Skip to content

Instantly share code, notes, and snippets.

@arunpersaud
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunpersaud/65e597b9b88c01a65f73 to your computer and use it in GitHub Desktop.
Save arunpersaud/65e597b9b88c01a65f73 to your computer and use it in GitHub Desktop.
how to simplify computed attributes
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