【发布时间】:2021-05-11 22:04:19
【问题描述】:
我根据在那里找到的AttrDict 创建了一个嵌套字典:
Object-like attribute access for nested dictionary
我将其修改为在“叶子”中包含str 命令,这些命令在请求/写入值时执行:
commands = {'root': {'com': {'read': 'READ_CMD', 'write': 'WRITE_CMD'} } }
class AttrTest()
def __init__:
self.__dict__['attr'] = AttrDict(commands)
test = AttrTest()
data = test.attr.root.com.read # data = value read with the command
test.attr.root.com.write = data # data = value written on the com port
虽然效果很好,但我想:
- 避免人们访问
attr/root/com,因为这会返回一个子级字典 - 直接访问
attr.root.com的人(通过__getattribute__/__setattr__)
目前,我面临以下问题:
- 如前所述,在访问嵌套字典的“主干”时,我得到了“叶子”的部分字典
- 访问
attr.root.com时返回{'read': 'READ_CMD', 'write': 'WRITE_CMD'} - 如果检测到
read,我会进行正向查找并返回值,但随后attr.root.com.read失败
是否有可能知道 Python 将在“路径”中请求的最终级别是什么?
- 阻止访问
attr/root - 直接读取/写入访问
attr.root.com的值(使用正向查找) - 仅在请求
attr.root.com.read或attr.root.com.write时返回所需的部分字典
目前我没有发现任何东西可以让我控制预期的查找深度。
感谢您的考虑。
【问题讨论】:
标签: python dictionary nested attributes