Last active
January 22, 2018 05:02
-
-
Save clarksun/609fedaf6ecce377a6c8032568ddc546 to your computer and use it in GitHub Desktop.
python dict用.来获取属性, 不用[]或者get
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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