オブジェクト名の文字列の最後にオブジェクトが必要だとしましょう: 文字列の例は で'first_class.second_class.third_class.id'
、文字列のリストはすべて の形式を取ります'X1object.X2object...XNobject.what_you_want_is_here_object'
。
いずれの場合も、特定の名前に関係なく、X1 オブジェクトのアクティブなインスタンスがあることがわかります。例の文字列では、コードは既に のインスタンスを呼び出していますfirst_class
。でロードでき、一般的にfirst_class
はでロードできます。globals['first_class']
X1object
globals['X1object']
必要なのは、文字列の最後にあるオブジェクト (通常は値) です。したがって、文字列の例では、 の値が必要ですid = first_class.second_class.third_class.id
。終了オブジェクトをフェッチするように文字列を変換する簡単な方法はありますか?
以下は、この問題を処理するために作成したコードですが、最後の属性が見つかるまで各属性を順番にフェッチするという力ずくのアプローチのようです。
first_class = FirstClass()
first_class = go_do_something_wild_in_first_class(first_class)
...
attribute = 'first_class.second_class.third_class.id'
attribute_pieces = attribute.split('.')
fetch_attribute = lambda attribute, name: \
attribute[name] if attribute == globals() else \
getattr(attribute, name)
for name in attribute_pieces: # I changed the code from using an index to using a name
if name == attribute_pieces[0]:
attribute = fetch_attribute(globals(), name)
else:
attribute = fetch_attribute(attribute, name)
id = attribute