像屬性一樣訪問字典鍵? - Accessing dict keys like an attribute?

語言: CN / TW / HK

問題:

I find it more convenient to access dict keys as obj.foo instead of obj['foo'] , so I wrote this snippet:我發現將 dict 鍵作為obj.foo而不是obj['foo']訪問更方便,所以我寫了這個片段:

class AttributeDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value

However, I assume that there must be some reason that Python doesn't provide this functionality out of the box.但是,我認為 Python 沒有提供這種現成的功能肯定是有原因的。 What would be the caveats and pitfalls of accessing dict keys in this manner?以這種方式訪問​​ dict 鍵的注意事項和陷阱是什麼?


解決方案:

參考一: https://stackoom.com/question/KujX
參考二: Accessing dict keys like an attribute?
「其他文章」