Skip to content

Instantly share code, notes, and snippets.

@zii
Last active September 11, 2016 05:05
Show Gist options
  • Save zii/773b26a2360b013feefc to your computer and use it in GitHub Desktop.
Save zii/773b26a2360b013feefc to your computer and use it in GitHub Desktop.
#coding: utf-8
class Struct(dict):
"""
- 为字典加上点语法. 例如:
>>> o = Struct({'a':1})
>>> o.a
>>> 1
>>> o.b
>>> None
"""
def __init__(self, *e, **f):
if e:
self.update(e[0])
if f:
self.update(f)
def __getattr__(self, name):
# Pickle is trying to get state from your object, and dict doesn't implement it.
# Your __getattr__ is being called with "__getstate__" to find that magic method,
# and returning None instead of raising AttributeError as it should.
if name.startswith('__'):
raise AttributeError
return self.get(name)
def __setattr__(self, name, val):
self[name] = val
def __hash__(self):
return id(self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment