小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

wrist friendly dictionary (Python recipe)

 dinghj 2014-04-24

wrist friendly dictionary (Python recipe)

5

this dictionary allows easy manual creation of nested hierarchies, like so:

window.style.width=5

or...

window['background-color'].rgb= 255,255,255

Python, 13 lines
Copy to clipboard
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class easyaccessdict(dict):
    def __getattr__(self,name):
        if name in self:
            return self[name]
        n=easyaccessdict()
        super().__setitem__(name, n)
        return n
    def __getitem__(self,name):
        if name not in self:
            super().__setitem__(name,nicedict())
        return super().__getitem__(name)
    def __setattr__(self,name,value):
        super().__setitem__(name,value)

By example:

>>> d= easyaccessdict()
>>> d
{}
>>> d.foo.bar= 'a'
>>> d
{'foo':{'bar':'a'}}
>>> d['foo']
{'bar':'a'}
>>> d['foo'].blah= 7
>>> d
{'foo':{'bar':'a', 'blah':7}}
>>> d.a.b.c.e.e.f.g.h= 11

etc.

Share

1 comment

Nezar Abdennur 8 months ago

Note that you can make this even terser by implementing __missing__:

class easyaccessdict(dict):
    def __getattr__(self, name):
        return self[name]
    def __setattr__(self, name, value):
        super().__setitem__(name,value)
    def __missing__(self, name):
        super().__setitem__(name, easyaccessdict())
        return super().__getitem__(name)

Also, super should be called using super(easyaccessdict, self) for this to work in python 2.

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多