是否有可能在python中捕获空的嵌套属性?

问题描述:

我想创建一个支持嵌套属性的自定义对象。是否有可能在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不存在于顶层。

你认为这是可能的吗?

非常感谢!

是的,这是可能的。在搜索例程中,重复到路径的末尾,检查所需的属性。在底层,返回属性,如果找到,否则。在每个非终端级别,再次下一级。

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 

这个伪代码是否让你朝着解决方案迈进?

+0

这很有趣 - 谢谢!我认为这是它可能在python中完成的唯一方法。可以使用autogen(例如jinja2)创建这样一个具有嵌套属性的类,然后可以像这样递归。我认为这是不可能的。 – lifer