Skip to content

Instantly share code, notes, and snippets.

@clarksun
Last active January 22, 2018 05:02
Show Gist options
  • Save clarksun/609fedaf6ecce377a6c8032568ddc546 to your computer and use it in GitHub Desktop.
Save clarksun/609fedaf6ecce377a6c8032568ddc546 to your computer and use it in GitHub Desktop.
python dict用.来获取属性, 不用[]或者get
# tornado.util.ObjectDict
# Makes a dictionary behave like an object, with attribute-style access.
import typing
_ObjectDictBase = typing.Dict[str, typing.Any]
class ObjectDict(_ObjectDictBase):
"""Makes a dictionary behave like an object, with attribute-style access.
"""
def __getattr__(self, name):
# type: (str) -> Any
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
# type: (str, Any) -> None
self[name] = value
# >>> a = ObjectDict()
# >>> isinstance(a, dict) # True
# >>> a.k1 = 'v1'
# >>> a.k2 = 2
# >>> a # {'k1': 'v1', 'k2': 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment