2
node.child1.child2
がある場合は、効果的にh asattr(node, 'child1.child2')
を使用できますか? child1
がない場合、または単にfalseを返すとエラーになりますか?hasattrは複数の子供をPythonで深く掘り下げることができますか?
node.child1.child2
がある場合は、効果的にh asattr(node, 'child1.child2')
を使用できますか? child1
がない場合、または単にfalseを返すとエラーになりますか?hasattrは複数の子供をPythonで深く掘り下げることができますか?
hasattr
は、そのような点線の名前をとらず、属性チェーンをナビゲートしません。しかし、あなたはそれを行うための関数を書くことができます。
def get_deep_attr(obj, attrs):
for attr in attrs.split("."):
obj = getattr(obj, attr)
return obj
def has_deep_attr(obj, attrs):
try:
get_deep_attr(obj, attrs)
return True
except AttributeError:
return False
ここでそれを行うための一つの方法だ:
def hasattrdeep(obj, *names):
for name in names:
if not hasattr(obj, name):
return False
obj = getattr(obj, name)
return True
はこのようにそれを呼び出します。
hasattrdeep(node) is True # A side-effect. Could be made invalid if really desired by raising TypeError if len(names) == 0
hasattrdeep(node, 'foo') is False
hasattrdeep(node, 'child1') is True
hasattrdeep(node, 'child1', 'foo') is False
hasattrdeep(node, 'child1', 'child2') is True
参照してください。それがどうなるか教えてください。 – aaronasterling
はい、実際にコードを実行して結果を投稿してください。 –