我有以下資訊結構:
items= {i1: {ref: i1_ref, attrs: {attr1: 'red', attr2: 'low'}}, i2: {ref: i2_def, attrs: {attr1: 'green', attr2: 'hight'}}}
i1, i2... 是字串。
i1_ref, i2_ref... 也是字串。
我想要一個i能夠檢索資訊的物件,如下所示:
i.i1從i1(i1_ref值)i.i2獲取 ref,從i2(i2_ref值)獲取 ref 。i.i1.attrs從 i1 獲取屬性的嵌套字典,i.i2.attrs從 i2 獲取屬性的嵌套字典。
代碼:
print(i.i1)
>>> i1_ref
print(i.i1.attrs)
>>> {attr1: 'red', attr2: 'low'}
uj5u.com熱心網友回復:
將屬性添加到 的子類str以獲得所需行為的解決方案。
items = {
"i1": {"ref": "i1_ref", "attrs": {"attr1": 'red', "attr2": 'low'}},
"i2": {"ref": "i2_def", "attrs": {"attr1": 'green', "attr2": 'hight'}}
}
# Subclass string, so we can add attributes to the instance.
class Item(str):
def __new__(cls, d):
s = super().__new__(cls, d["ref"])
s.attrs = d["attrs"]
return s
# Just a class that holds the dict keys as attributes
# and Item objects as their values.
class Items:
def __init__(self, d):
for it in d:
setattr(self, it, Item(d[it]))
i = Items(items)
print(i.i1)
print(i.i1.attrs)
輸出:
i1_ref
{'attr1': 'red', 'attr2': 'low'}
不同的解決方案SimpleNamespace:
from types import SimpleNamespace
items = {
"i1": {"ref": "i1_ref", "attrs": {"attr1": 'red', "attr2": 'low'}},
"i2": {"ref": "i2_def", "attrs": {"attr1": 'green', "attr2": 'hight'}}
}
class Item(SimpleNamespace):
def __str__(self):
return self.ref
i = SimpleNamespace(**{k:Item(**v) for k,v in items.items()})
print(i.i1)
print(i.i1.attrs)
雖然列印的輸出完全相同,但行為有點不同:
雖然i.i1第一個解決方案確實是一個字串(帶有附加的attrs),i.i1但第二個解決方案是一個SimpleNamespace物件,其字串表示為ref。
這意味著i.i1 == "i1_ref"是True第一個解決方案,但對于第二個解決方案,你需要寫str(i.i1) == "i1_ref"或i.i1.ref == "i1_ref"。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404580.html
標籤:
下一篇:Julia中的排序字典
