2016-10-25 4 views
1

ネストされた属性をサポートするカスタムオブジェクトを作成しようとしています。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が最低レベル(config.random.path.to)に存在するかどうかを確認する代わりに、ある

important key is: important_value 
random 
path 
to 
important_key 
{} 

、その後、レベル(config.random.path)に上がると、それは場合にのみNoneを返しますトップレベルには存在しません。

これは可能ですか?

ありがとうございました!

答えて

0

はい、可能です。検索ルーチンで、パスの最後に再帰し、目的の属性があるかどうかを確認します。一番下のレベルで、見つかった場合は属性なしを返します。各非終端レベルで、次のレベルに戻る。

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

関連する問題