Skip to content

Instantly share code, notes, and snippets.

@SureshKL
Created December 18, 2018 03:48
Show Gist options
  • Save SureshKL/9b72931f5c223759b2cd4b6de3db431e to your computer and use it in GitHub Desktop.
Save SureshKL/9b72931f5c223759b2cd4b6de3db431e to your computer and use it in GitHub Desktop.
Attribute Lookup
import sys
class CommonAttributes:
def __init__(self):
self.name = 'common'
class MissingAttributes:
def __init__(self):
self.name = 'missing'
class GetterSpecialMethods(CommonAttributes):
name = 'class variable'
def __init__(self):
super().__init__()
this_func = sys._getframe().f_code.co_name
print(f'Called {this_func} method to initialize class')
self.name = 'Suresh'
def __getattribute__(self, item):
this_func = sys._getframe().f_code.co_name
print(f'Called overridden method {this_func} for attribute lookup')
if item not in super().__dict__:
raise AttributeError(f'Attribute not found via {this_func}')
# any other exception will abort, AttributeError will cause the lookup to continue via __getattr__
return super().__dict__.get(item)
def __getattr__(self, item):
this_func = sys._getframe().f_code.co_name
print(f'Called {this_func} for missing attribute')
if item not in MissingAttributes().__dict__:
raise AttributeError(f'Attribute not found via {this_func}')
MissingAttributes().__dict__.get(item)
def __getitem__(self, item):
this_func = sys._getframe().f_code.co_name
print(f'Called {this_func} for subscript notation')
return self.__dict__.get(item)
# def __get__(self, instance, owner):
# pass
#
# def __getinitargs__(self):
# pass
#
# def __getnewargs__(self):
# pass
#
# def __getstate__(self):
# pass
getter_obj = GetterSpecialMethods()
print(getter_obj.name)
print(getter_obj.name_not_found)
print(getter_obj['name'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment