Skip to content

Instantly share code, notes, and snippets.

@weaming
Created March 10, 2017 10:02
Show Gist options
  • Select an option

  • Save weaming/3f5c7ff890b49f0ce86c778aeec8e092 to your computer and use it in GitHub Desktop.

Select an option

Save weaming/3f5c7ff890b49f0ce86c778aeec8e092 to your computer and use it in GitHub Desktop.
Make a dict or a dict to be object.
class Objectify(object):
def __init__(self, data):
""" data maybe one dict or list """
self.data = data
def __getitem__(self, item):
_data = object.__getattribute__(self, 'data')
return _data[item]
def __getattribute__(self, item):
_data = object.__getattribute__(self, 'data')
if hasattr(_data, item):
# 调用本身的方法
return getattr(_data, item)
return _data[item]
def __getattr__(self, item):
# 默认返回None
return None
def __len__(self):
_data = object.__getattribute__(self, 'data')
return len(_data)
def __iter__(self):
_data = object.__getattribute__(self, 'data')
for i in _data:
if isinstance(i, dict):
yield Objectify(i)
else:
yield i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment