簡體   English   中英

是否可以在python中捕獲空的嵌套屬性?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM