0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

辞書の値を属性参照するメモ(車輪の再開発)

Last updated at Posted at 2020-11-20

AttrDictの方が便利だけど、ちょっと使いたいのにインストールしたくない人向け(22/10/16更新)

値の参照だけしたいとき

定義

class Dict(dict):__getattr__=dict.__getitem__

要素の追加もできるように__setattr__を追加したバージョン。

class Dict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__

使用時

a = Dict(a=0, b=Dict(c=1, d=2))
(a.a, a.b.c, a["a"], a["b"]["c"])

値も設定したい

定義

class Dict(dict):__getattr__=dict.__getitem__;__setattr__=dict.__setitem__

一行で書く必要はないけど。

使用時

a = Dict()
a.b = Dict()
a.b.c = True
a.b.d = True
a.b["c"] = False
a.b.d = False
print(a)

pickleで使いたいとき

定義

class Dict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    
    def __getstate__(self):
        return self.__dict__.copy()

    def __setstate__(self, state):
        self.__dict__.update(state)

__getstate__, __setstate__をpickle対策のため追加

使用時

import pickle
a = Dict(a=0, b=Dict(c=1, d=2))
a.b.e = False
(a, (a.a, a.b.c, a["a"], a["b"]["c"]), pickle.loads(pickle.dumps(a)))

番外編

式で書いてみる。特に意味はない。

globals().update({"Dict": type("Dict", (dict,), dict(__getattr__=dict.__getitem__, __setattr__=dict.__setitem__))}); a=Dict(a=1, b=Dict(c=2, d=3)); a.b.e=4; a
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?