[英]Is it possible to catch empty nested attributes in python?
我正在尝试创建一个支持嵌套属性的自定义对象。
我需要实现一种特定的搜索。
如果某个属性在最低级别不存在,我想递归并查看该属性是否存在于更高级别。
我整天都在努力做到这一点。 我最接近的是能够打印属性搜索路径。
class MyDict(dict):
def __init__(self):
super(MyDict, self).__init__()
def __getattr__(self, name):
return self.__getitem__(name)
def __getitem__(self, name):
if name not in self:
print name
self[name] = MyDict()
return super(MyDict, self).__getitem__(name)
config = MyDict()
config.important_key = 'important_value'
print 'important key is: ', config.important_key
print config.random.path.to.important_key
输出:
important key is: important_value
random
path
to
important_key
{}
我需要做的是查看important_key
存在于最低级别( config.random.path.to
),然后上升到一个级别( config.random.path
)并且只有在它不存在时才返回None
。顶层。
你认为这有可能吗?
非常感谢!
是的,这是可能的。 在搜索例程中,重复到路径的末尾,检查所需的属性。 在底层,如果找到则返回属性,否则返回None 。 在每个非终端级别,重复到下一级别。
if end of path # base case
if attribute exists here
return attribute
else
return None
else # some upper level
exists_lower = search(next level down)
if exists_lower
return exists_lower
else
if attribute exists here
return attribute
else
return None
这个伪代码是否会让您转向解决方案?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.