Skip to content

Instantly share code, notes, and snippets.

@geekKeen
Created December 26, 2017 03:23
Show Gist options
  • Save geekKeen/a0d6151e11585e9b08a98b9d4601227d to your computer and use it in GitHub Desktop.
Save geekKeen/a0d6151e11585e9b08a98b9d4601227d to your computer and use it in GitHub Desktop.
Object attr
class MemoizedSlots(object):
def _fallback_getattr(self, key):
raise AttributeError(key)
def __getattr__(self, key):
if key.startswith('_memoized'):
raise AttributeError(key)
elif hasattr(self, '_memoized_attr_%s' % key):
value = getattr(self, '_memoized_attr_%s' % key)()
setattr(self, key, value)
return value
elif hasattr(self, '_memoized_method_%s' % key):
fn = getattr(self, '_memoized_method_%s' % key)
def onshot(*args, **kwargs):
result = fn(*args, *kwargs)
memo = lambda *args, **kwargs: result
memo.__doc__ = fn.__doc__
memo.__name__ = fn.__name__
setattr(self, key, memo)
return result
onshot.__doc__ = fn.__doc__
return onshot
else:
self._fallback_getattr(key)
m = lambad *args, **kwargs: return
@geekKeen
Copy link
Author

geekKeen commented Dec 26, 2017

memorized_solts.py

Q:getattr, getattr 的作用?
A:

  1. getattr(self, 'foo') == self.foo
  2. `__getattr__` 的调用情况: instance 先在自己的属性中找如果找到则不调用, 但是如果没找到,则会调用 `__getattr__`. 因此 `__getattr__ `是找`type(instance)`的属性. 根据 getattr()  的说明,如果调用不好,就会出现递归情况出现
  3. 深入: getattribute 是无条件调用,则instance的任何属性都会调用他 ,只有在此调用 raise AttributeError 时才会调用__getattr__
    4.setattr/ setattr: setattr(self, 'foo', 1) == self.foo=1, setattr 会在instance attribute dict 添加, 如果在__setattr__ 中做self.name='foo', 将会出现递归

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment