如下是對yaml解析器的進階封裝,使用了面向對象的思想。
demo.yml檔案中的内容:
test:
a:
b: dashuai
封裝代碼
import yaml
class YamlOperation(dict):
def __init__(self, file_path=None, content=None):
super().__init__()
if file_path is not None:
with open(file_path, "r")as file:
content = yaml.load(file, Loader=yaml.SafeLoader)
content = content if content is not None else {}
# content = [content, {}][not content]
# content = (not content and content or {})
for key, value in content.items():
if isinstance(value, dict):
self[key] = YamlOperation(content=value)
else:
self[key] = value
def __getattr__(self, key):
"""通路不存在的屬性key時傳回None"""
return None
def __setattr__(self, key, value):
"""設定執行個體屬性值"""
self[key] = value
def __setitem__(self, key, value):
"""給self[key]指派"""
super().__setattr__(key, value)
super().__setitem__(key, value)
def __missing__(self, key):
"""通路的鍵key不存在時,傳回None"""
return None
if __name__ == '__main__':
data = YamlOperation("demo.yml")
print(data.test) # 輸出:{'a': {'b': 'dashuai'}}
print(data['test']) # 輸出:{'a': {'b': 'dashuai'}}
print(data.get('test')) # 輸出:{'a': {'b': 'dashuai'}}
print(data.test.a.b) # 輸出:dashuai
print(data.a) # 調用__getattr__ 傳回None
print(data['a']) # 調用__missing__ 傳回None
說明:代碼中定義了YamlOperation類,繼承了dict字典,并重寫了幾個帶__的魔法方法。魔法方法的使用參考:python魔法方法、内置方法詳解,執行個體化類的對象後,可以用.屬性的方式通路。