这个异常处理明显有问题会抛出异常两次。 return self[key] 如果 key 不存在直接就会抛异常了,后面又人工抛一次,体验不太好。 还不如下面的方案, value = self.get(key, KeyError(k)) if isinstance(value, KeyError): raise AttributeError(k)
应该有更好的方案我只是举例说一下。 另外就是是不是考虑多层字典 AttrDict 嵌套的方案。
d = AttrDict(abc={'a': 1}, d=True) d.abc.a 怎么样?
if isinstance(value, dict): value = AttrDict(value) return value
xpresslink
2017-12-29 11:16:48 +08:00
@est 在 python2 里返回就是 list,python3 改成的 iterator 实际上造轮子是很难的,要解决众多版本特性差异问题。 官方说了不要把 3.6 的字典有序当成可以确保的事儿。 docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation > The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).