如何使用@属性访问嵌套字典

How to access nested dict using @property

我可以使用以下代码使用@属性装饰器来设置class属性,但是我无法设置属性(在层次结构中)以防它是嵌套字典. 例如,如果我们需要打印嵌套 'credentials' 字典中的 'port' 的值,那么我该如何使用 print(obj.credentials.port) 而不是使用 print(obj.port)

class TestDec:
    def __init__(self,value) -> None:
        self.value = value
    @property
    def description(self):
        return self.value["description"]
    @property
    def credentials(self):
        return self.value["credentials"]
    @property
    def username(self):
        return self.value["credentials"]["username"]  
    @property
    def password(self):
        return self.value["credentials"]["password"]   
    @property
    def port(self):
        try:
            return self.value["credentials"]["port"]      
        except KeyError:
            pass                    

obj = TestDec({"description":"test decorator","credentials":{"username":"abc","password":"xxxx","port":"5432"}})
print(obj.description)
print(obj.credentials)
print(obj.username)
print(obj.password)
print(obj.port)

要么你在 obj.username 和类似的错误,它应该是 obj.credentials.username(就像我下面的例子),或者你想递归搜索键,我不认为是个好主意。但是对于这个嵌套的点访问字典元素,这可能就足够了。

from collections import UserDict


class MyDict(UserDict):
    def __getattr__(self, arg):
        try:
            result = self.data[arg]
        except KeyError as error:
            raise AttributeError from error

        if isinstance(result, dict):
            return MyDict(result)
        return result


obj = MyDict(
    {
        "description": "test decorator",
        "credentials": {"username": "abc", "password": "xxxx", "port": "5432"},
    }
)
print(obj.description)
print(obj.credentials)
print(obj.credentials.username)
print(obj.credentials.password)
print(obj.credentials.port)