dictとlistをほげほげ

メモ。

class MyResolver(object):
    def __init__(self, obj):
        self.obj = obj
    def __getattr__(self, key, default=None):
        if isinstance(self.obj, list) or isinstance(self.obj, dict):
            if key and not key.startswith('__') and key.startswith('_'):
                return MyResolver(self.obj[int(key[1:])])
            if self.obj.has_key(key):
                return MyResolver(self.obj[key])
        return getattr(self.obj, key)
    def __getitem__(self, key):
        obj = self.obj[key]
        if isinstance(self.obj, list) or isinstance(self.obj, dict):
            return MyResolver(obj)
        else:
            return obj
    def __str__(self):
        return str(self.obj)
    def __unicode__(self, *args, **kwargs):
        return unicode(self.obj, *args, **kwargs)
>>> o = MyResolver({'foo': {'bar': [{'hoge': ['tokibito', 'nullpobug']}]}})

>>> print o.foo.bar
[{'hoge': ['tokibito', 'nullpobug']}]

>>> print o.foo.bar._0.hoge._1
nullpobug

>>> print o.foo.bar[0].hoge[1]
nullpobug

"__xxx__"なメソッドはいろいろできて面白いね。